1

I have the table tbl_relations with columns

id,user_name,relation_name,relation_name_id 

tbl_relations table

relation_name_id is the foreign key referencing id in the same table.
In laravel I will select two inputs from id and need to get the collections of data from input one to till it's reach the second input using foreign key recursive method..is it possible?

This way I need to get the collection

Qirel
  • 25,449
  • 7
  • 45
  • 62
  • 1
    You will have to need to use MySQL's 8 CTE and recursive queries that is your best option with this data model. – Raymond Nijland Mar 22 '19 at 11:06
  • @RaymondNijland will you please convert this into laravel https://stackoverflow.com/questions/16542013/symbol-a-solution-for-recursive-select-query-in-mysql – Piruthivi Raj Mar 25 '19 at 02:24

1 Answers1

2

This solution is probably inefficient but it will work:

class Relation extends Model {
     protected $table = 'tbl_relations';
     protected $with = [ 'related' ];

     public function related() {
          return $this->hasOne(Relation::class, 'relation_name_id'); 
     }
}

Each time the Relation model is loaded it should trigger a loading of the related relation.

You can then do:

Relation::find(1)->related->related->id;

Note this solution does not take into account specific MySQL optimizations so will probably be the slowest possible solution.

apokryfos
  • 38,771
  • 9
  • 70
  • 114
  • Thanks a lot but "Trying to get property 'related' of non-object " getting this error brother – Piruthivi Raj Mar 22 '19 at 11:26
  • I think it's to do with the direction. The idea is `Relation` **has** another relation meaning there's some relation where its `relation_name_id` is the id of this relation. In my example I used `1` as the ID but based on what you shared that probably won't work, however `Realtion::find(2)->relation->id` will probably return `1` – apokryfos Mar 22 '19 at 11:39