laravel eloquent join 如何使用 scope ?

有两个表

表 user

idname
1tom
2jerry

表 friend

iduser_idsupport_id
111
212

表 support

idnamecan_fly
1bird1
2dog0

三个 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}
阅读 2.1k
1 个回答

你可以在 Friend 模型中定义一个新的本地作用域,结合 with 和 whereHas 方法实现:

class Friend extends Model
{
    public function user()
    {
        return $this->belongsTo(User::class);
    }

    public function support()
    {
        return $this->belongsTo(Support::class);
    }

    public function scopeWithFlySupport($query)
    {
        return $query->whereHas('support', function ($query) {
            $query->fly();
        });
    }
}

现在,你可以在查询中用 withFlySupport 作用域:

$user = User::find(1);
$friendsWithFlySupport = $user->friends()->withFlySupport()->get();
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进