【问题标题】:Laravel add where clause to union resultLaravel 在联合结果中添加 where 子句
【发布时间】:2016-09-21 09:11:14
【问题描述】:

我正在对两个查询进行联合,我想在结果中添加 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();

我想要这条线

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

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

【问题讨论】:

  • 你不能在两个查询中添加->where('brand_id', '=', '2'),并在unionAll 之前添加第二个(并删除brand_ids where 子句)?

标签: php mysql laravel laravel-5 union


【解决方案1】:

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

$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();

【讨论】:

  • 希望有更好的方法
猜你喜欢
  • 2019-06-26
  • 1970-01-01
  • 2017-11-12
  • 1970-01-01
  • 1970-01-01
  • 2022-08-05
  • 1970-01-01
  • 1970-01-01
  • 2019-05-21
相关资源
最近更新 更多