Laravel将union子句添加到union结果中

时间:2021-05-03 11:52:32

I'm doing a union on two queries, and I want to add a where clause to the result, but the where clause is added only to the first query. how can I fix that?

我正在对两个查询进行联合,我想在结果中添加一个where子句,但是where子句只添加到第一个查询中。我怎么解决这个问题?

    $notifications = DB::table('notifications')
        ->select(DB::raw("notifications.uuid ,notifications.brand_id" ))
    $posts = DB::table('posts')
        ->select(DB::raw("posts.uuid ,posts.brand_id" ))
        ->unionAll ($notifications)
        ->orderBy('created_at' , 'desc')
        ->where('brand_ids' , '=' , '2')
    $result  = $posts->get();

I want this line

我想要这一行

           ->where('brand_id' , '=' , '2')

to be added to the whole union, but it is added only to one of the queries.

要添加到整个联合,但它只添加到其中一个查询。

1 个解决方案

#1


0  

I am not sure if there is a better way, but this works for me:

我不确定是否有更好的方法,但这对我有用:

$notifications = DB::table('notifications')
                ->select(DB::raw("notifications.uuid ,notifications.brand_id"));
$posts = DB::table('posts')
        ->select(DB::raw("posts.uuid ,posts.brand_id"))
        ->unionAll($notifications)
        ->orderBy('created_at' , 'desc');
$result = DB::table(DB::raw("({$posts->toSql()}) as posts"))
                ->mergeBindings($posts)
                ->where('brand_id', '2')
                ->get();

#1


0  

I am not sure if there is a better way, but this works for me:

我不确定是否有更好的方法,但这对我有用:

$notifications = DB::table('notifications')
                ->select(DB::raw("notifications.uuid ,notifications.brand_id"));
$posts = DB::table('posts')
        ->select(DB::raw("posts.uuid ,posts.brand_id"))
        ->unionAll($notifications)
        ->orderBy('created_at' , 'desc');
$result = DB::table(DB::raw("({$posts->toSql()}) as posts"))
                ->mergeBindings($posts)
                ->where('brand_id', '2')
                ->get();