通过优先级在单个laravel查询中进行多次选择查询

时间:2018-12-30 12:55:53

标签: php mysql laravel

我想将此查询语句转换为laravel查询生成器 分页

"SELECT images.*,categories.name,categories.slug   FROM ( SELECT 1 AS rnk, images.* FROM images WHERE title REGEXP '[[:<:]]{$q}[[:>:]]' 
                                UNION SELECT 2 AS rnk, images.* FROM images WHERE tags REGEXP '[[:<:]]{$q}[[:>:]]' ) images
                                inner join categories on categories.id = images.categories_id
                                where status = 'active' ORDER BY rnk"

我使用laravel 5.3

1 个答案:

答案 0 :(得分:0)

完成;)

            $subquery  = "( SELECT 1 AS rnk, images.* FROM images WHERE title REGEXP '[[:<:]]{$q}[[:>:]]' 
                            UNION SELECT 2 AS rnk, images.* FROM images WHERE tags REGEXP '[[:<:]]{$q}[[:>:]]') query";
        $images    = Images::select(['categories.name', 'categories.slug', 'images.*'])
                        ->join('categories', 'images.categories_id', '=', 'categories.id')
                        ->join(\DB::raw($subquery), 'query.id', '=', 'images.id')
                        ->where('images.status', 'active' )
                        ->groupBy('images.id')
                        ->orderBy('query.rnk' )
                        ->paginate( $settings->result_request )
                        ->appends(request()->query());