我有两个表,分别命名为students
和cities
。 students
表具有一个与cities
表相关的主键。
在前端,我希望满足以下要求的cities
表数据:
students
表中的数据必须按city_id
分组city_id
表中有多个记录具有相同的students
,则仅选择组中的最新记录。这是city
模型的关系函数:
public function student()
{
return $this->hasOne(Student::class, 'city_id', 'id')->orderByDesc('id');
}
这是我的控制器功能:
$data = City::whereHas('student', function($query){
$query->where('is_active', 0)
})->with('student')->get();
预期结果::考虑到样本数据,查询必须不返回任何内容。
当前结果:由于第二行中有不活动的学生记录,因此它返回第三行。因此,在这种情况下,where
条件无法正常工作。
我可以通过以下SQL查询获得预期结果:
select *
from students s
where id = (select max(t2.id)
from students s2
where s.city_id = s2.city_id) AND is_active = '0';
如何解决此逻辑错误?
答案 0 :(得分:0)
这样的事情怎么办?
public function inactiveStudent()
{
return $this->hasOne(Student::class, 'city_id', 'id')
->where('is_active', 0)
->orderByDesc('id');
}
$data = City::whereHas('inactive_student')
->with('inactive_student')
->get();
查询时不确定是inactive_student
还是inactiveStudent
。