Recursive foreign key in laravel [duplicate]

问题: This question already has an answer here: How to create a MySQL hierarchical recursive query 15 answers I have the table tbl_relations with columns...

问题:

This question already has an answer here:

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


回答1:

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.

  • 发表于 2019-03-27 03:51
  • 阅读 ( 162 )
  • 分类:sof

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除