有两个表
表 user
id | name |
---|---|
1 | tom |
2 | jerry |
表 friend
id | user_id | support_id |
---|---|---|
1 | 1 | 1 |
2 | 1 | 2 |
表 support
id | name | can_fly |
---|---|---|
1 | bird | 1 |
2 | dog | 0 |
三个 Model
class User extends Model{
public function friends()
{
return $this->hasMany(Friend::class);
}
}
class Friend extends Model{
public function user()
{
return $this->belongsTo(User::class);
}
public function support()
{
return $this->belongsTo(Support::class);
}
}
class Support extends Model{
public function scopeFly($query)
{
return $query->where('can_fly', 1);
}
}
我想实现如下 sql,意义为 获取 tom 所有会飞的朋友 关系
select * from friend
inner join support on friend.support_id = support.id
inner join user on friend.user_id = user.id
where user.id = 1
and where support.can_fly = 1
我这样写,但后边的不会写了,求解。
$user = User::find(1);
$user->friends()-> {how to inner join support} -> {how to use support's scopeFly}
你可以在 Friend 模型中定义一个新的本地作用域,结合 with 和 whereHas 方法实现:
现在,你可以在查询中用 withFlySupport 作用域: