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

2
  • 1
    You will have to need to use MySQL's 8 CTE and recursive queries that is your best option with this data model. Commented Mar 22, 2019 at 11:06
  • @RaymondNijland will you please convert this into laravel stackoverflow.com/questions/16542013/… Commented Mar 25, 2019 at 2:24

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks a lot but "Trying to get property 'related' of non-object " getting this error brother
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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.