条件表连接

时间:2015-09-20 06:45:07

标签: laravel join laravel-5 eloquent laravel-5.1

我在我雄辩的模型中有以下范围,我想为它添加两个条件。这样做我需要帮助。

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表包含featuredsort列。我想选择返回结果的images.featured is 1min sort的一行。如果没有images.featured=1,那么我想选择min of sort

目前,上述范围为每个min sort

选择vessel_id的图片

2 个答案:

答案 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"));
}