自我参与雄辩 [英] Self Join in Eloquent

查看:130
本文介绍了自我参与雄辩的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你如何写出一个有力的自我参与?我需要在模型上定义关系吗?



这是我的说法:

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


解决方案

您可以简单地定义与自己的关系。 >

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

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


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

解决方案

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');
}

这篇关于自我参与雄辩的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆