Laravel 8 unionAll()与orderBy不起作用

cidc1ykv  于 2023-06-25  发布在  其他
关注(0)|答案(1)|浏览(176)

我有两个模型需要得到工会选择。简单的unionAll工作,但如果我需要按选定列排序结果,它不工作。Laravel代码看起来像

$events = Event::select('id', 'event_name as name', 'publish_at', DB::raw("'EVENT' as type"))
        ->customer($id)
        ->orderBy('publish_at', 'asc');

    $news = News::select('id', 'name', 'publish_at', DB::raw("'NEWS' as type"))
        ->customer($id)
        ->orderBy('publish_at', 'asc')
        ->unionAll($events)
        ->orderBy('publish_at');

此女生的SQL转储如下所示:

(
    select "id", "name", "publish_at", 'NEWS' as type
    from "news" where exists 
        (
            select * from "customers"
            inner join "news_customers" 
            on "customers"."id" = news_customers"."customer_id"
            where "news"."id" = "news_customers"."news_id" 
            and "news_customers"."customer_id" = 3
        ) 
    order by "publish_at" asc
)    
union all    
(
    select "id", "event_name" as "name", "publish_at", 'EVENT' as type
    from "events" where exists 
    (
        select * from "customers" 
        inner join "event_customers" 
        on "customers"."id" = "event_customers"."customer_id" 
        where "events"."id" = "event_customers"."event_id" 
        and "event_customers"."customer_id" = 3
    )
    order by "publish_at" asc
) 
order by "publish_at" asc
k5ifujac

k5ifujac1#

可以使用子查询按publish_at列对联合结果排序。

$subQuery = $events->toSql(); // Get the SQL query from the $events query builder

$news = News::select('id', 'name', 'publish_at', DB::raw("'NEWS' as type"))
    ->customer($id)
    ->orderBy('publish_at', 'asc')
    ->unionAll(DB::table(DB::raw("($subQuery) as sub")))
    ->orderBy('publish_at', 'asc');

相关问题