Laravel雄辩的多个搜索过滤器

时间:2018-10-07 06:31:10

标签: mysql laravel-5 laravel-5.4

鉴于以下查询,您如何添加更多where / add(mysql)字段条件,最多4个字段?

$query = Profile::select('field1', field2', 'field3, 'field4', DB::raw('SUM(likes.like) AS total'))
        ->leftJoin('users', 'users.id', '=', 'profiles.user_id')
        ->leftJoin('likes', 'likes.profile_id', '=', 'profiles.user_id')
        ->whereNotNull('users.id')
        ->groupBy('users.id')
        ->orderBy('users.last_login_at', 'DESC')
        ->get();

我尝试如下添加,导致405错误:

    $query = Profile::select('field1', field2', 'field3, 'field4', DB::raw('SUM(likes.like) AS total'))
            ->leftJoin('users', 'users.id', '=', 'profiles.user_id')
            ->leftJoin('likes', 'likes.profile_id', '=', 'profiles.user_id')
            ->whereNotNull('users.id');

    if ($field1 != 'condition') {    
        $query->where('profiles.field1', $field1)
    }
            $query->groupBy('users.id')
            ->orderBy('users.last_login_at', 'DESC')
            ->get();

1 个答案:

答案 0 :(得分:1)

您的选择语句中有错误。

 $query = Profile::select('field1', 'field2', 'field3', 'field4', "DB::raw('SUM(likes.like) AS total')")
        ->leftJoin('users', 'users.id', '=', 'profiles.user_id')
        ->leftJoin('likes', 'likes.profile_id', '=', 'profiles.user_id')
        ->where('users.id', "!=", '');

if ($field1 != 'condition') {    
   $query = $query->where('profiles.field1', $field1)
}
        $query = $query->groupBy('users.id')
        ->orderBy('users.last_login_at', 'DESC')
        ->get();

将附加值分配给同一变量$query