Self Join in Eloquent

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-22 05:36:16

问题


How would you write a self join in eloquent? Would I need to define the relationship on the model?

Here's my statement:

SELECT t2.title FROM products t1, products t2
WHERE t1.id = $id 
AND t2.color_id = t1.color_id AND
t2.id != $id

回答1:


You can simply define a relation to itself.

public function parent()
{
    return $this->belongsTo(self::class, 'color_id');
}

public function children()
{
    return $this->hasMany(self::class, 'color_id');
}


来源:https://stackoverflow.com/questions/30592793/self-join-in-eloquent

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!