我有两个表,school_users
和users
。我需要使用Eloquent创建一个查询,以使所有用户都user_id
相等school_id
。因此结果必须超过一个用户,因此我还需要按school_id对结果进行分组
谢谢你的勇敢
关系:用户模型:
public function school()
{
return $this->hasMany(SchoolUser::class);
}
学校用户模型:
public function user()
{
return $this->hasMany(User::class);
}
School_users
表:
+----+---------+------------+-------------+
| id | user_id | school_id | created_at |
+----+---------+------------+-------------+
| 1 | 79 | 79 | <SOME TIME> |
| 2 | 85 | 79 | <SOME TIME> |
| 3 | 86 | 85 | <SOME TIME> |
| 4 | 87 | 85 | <SOME TIME> |
+----+---------+------------+-------------+
users
表:
+----+
| id |
+----+-
| 79 |
| 85 |
| 86 |
| 87 |
+----+-
用户模型:
public function getUsers()
{
return $this
->leftJoin('school_users', $this->table . '.id', '=', 'school_users.school_id')
->select(
$this->table . '.*',
'school_users.school_id as school_id'
)
->whereIn('users.id', '=', 'school_users.school_id')
->orderBy('id', 'desc')
->get();
}
使用whereColumn
进行筛选user_id
等于school_id
,
并使用join
代替leftjoin
:
public function getUsers()
{
return $this
->join('school_users', function($join) {
$join->on('school_users.user_id', '=', $this->table.'.id')
->whereColumn('school_users.user_id', 'school_users.school_id');
})
->select
(
$this->table.'.*',
'school_users.school_id as school_id'
)
->orderBy($this->table.'.id','desc')
->get();
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句