我在我雄辩的模型中有以下范围,我想为它添加两个条件。这样做我需要帮助。
public function scopeImages($query) {
$query->join('images as i', function ($join) {
$join->on('i.vessel_id', '=', 'vessel.id')
->where('i.sort', '=', 'min(i.sort)');
})
->leftjoin('users', 'users.id', '=', 'vessel.user_id')
->select('vessel.*', 'i.image as image', 'users.name as brokername');
}
images
表包含featured
和sort
列。我想选择返回结果的images.featured is 1
和min sort
的一行。如果没有images.featured=1
,那么我想选择min of sort
。
目前,上述范围为每个min sort
vessel_id
的图片
答案 0 :(得分:0)
如果您在desc中按特色(如果特色是布尔值)订购并在asc中排序,它将列出最高优先级的特色1,然后列出从最小到最大的排序。现在,如果你采取第一行,你将得到你想要的。
$query->join('images', 'images.vessel_id', '=', 'vessel.id')
->leftjoin('users', 'users.id' ,'=', 'vessel.user_id')
->select('vessel.*', 'images.image as image', 'users.name as brokername')
->orderBy('images.featured', 'DESC')
->orderBy('images.sort', 'ASC')
->take(1);
答案 1 :(得分:0)
您需要一个相关的子查询
https://dev.mysql.com/doc/refman/5.5/en/correlated-subqueries.html
SELECT v.*,
(SELECT `image` FROM images WHERE vessel_id = v.id ORDER BY featured DESC, sort LIMIT 1) AS image
FROM `vessel` AS v
@EDIT 你可以尝试一下:
public function scopeImages($query) {
return $query
->leftjoin('users', 'users.id', '=', 'vessel.user_id')
->select(\DB::raw("vessel.*, (SELECT `image` FROM images WHERE vessel_id = vessel.id ORDER BY featured DESC, sort LIMIT 1) AS image, users.name as brokername"));
}