php - Laravel 将 where 子句添加到联合结果

标签 php mysql laravel laravel-5 union

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

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

最佳答案

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

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

关于php - Laravel 将 where 子句添加到联合结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37408758/

相关文章:

php - PayPal API Express Checkout 获取响应

Php 文件输出变量

c# - 如何使用 Entity Framework 批量插入与外键相关的多个表

Laravel, Eloquent n :m relationship

AngularJS:用户身份验证后重新加载 ng-include (或解决问题的更好方法)

laravel - 在 Laravel 中找不到迁移回滚错误类

PHP-Memcached : MySql resource caching

php - 从 mysql 中以逗号分隔的字符串获取特定值

php - Count/Group By/Order By 只显示最常见值的计数而不是字符串本身

mysql - 当同一数据库中的另一个表被更改时,如何更改 mysql 数据库表?