Laravel 查询生成器联合:添加“表名称”列

问题描述 投票:0回答:2

有 3 个不同的数据库表

articles
reviews
posts
,所有这些表都有以下列:
'id', 'title', 'user_id', 'created_at', 'body'

我正在使用 Laravel 5.6 和 yajra/laravel-datatables 包,所以我需要“联合”这三个表并将其放入 jQuery DataTables 中。 为此,我使用 Laravel 的

union
查询生成器方法:

    $fields = [
        'id',
        'title',
        'user_id', 
        'created_at',
        'body'
    ];

    $articles = DB::table('articles')->select($fields);
    $reviews = DB::table('reviews')->select($fields);
    $posts = DB::table('posts')->select($fields);

    $union = $articles->union($reviews)->union($posts)->get();

    dd($union);

...这工作正常,结果如下所示:

+----+-------------+---------+------------+------+
| id |    title    | user_id | created_at | body |
+----+-------------+---------+------------+------+
|  1 | Some title  |       1 | ...        | ...  |
|  1 | Lorem ipsum |       2 | ...        | ...  |
|  1 | Test        |       1 | ...        | ...  |
+----+-------------+---------+------------+------+

问题是我需要知道每条记录(行)来自哪个表。 是否可以添加包含数据库表名称的自定义列(例如“源”)? (使用查询生成器)

+----+-------------+---------+------------+------+----------+
| id |    title    | user_id | created_at | body |  source  |
+----+-------------+---------+------------+------+----------+
|  1 | Some title  |       1 | ...        | ...  | articles |
|  1 | Lorem ipsum |       2 | ...        | ...  | reviews  |
|  1 | Test        |       1 | ...        | ...  | posts    |
+----+-------------+---------+------------+------+----------+
php mysql laravel union laravel-query-builder
2个回答
3
投票

DB::raw
自定义字段添加到
fields
内的
select
数组,例如:

$articles = DB::table('articles')->select(array_merge($fields, [DB::raw('"articles" as source')]));
$reviews = DB::table('reviews')->select(array_merge($fields, [DB::raw('"reviews" as source')]));
$posts = DB::table('posts')->select(array_merge($fields, [DB::raw('"posts" as source')]));

这应该将

source
字段添加到您的结果集中


1
投票

没有函数可以返回作为行源的表。例如,如果您有一个 JOIN,它必须返回一个列表,并且派生表子查询等会使它变得更加复杂。

在 UNION 中执行此操作的方法是使用用于命名表的字符串常量向 UNION 中的每个查询添加自定义列。

SELECT 'articles' as table_name, id, title, user_id, created_at, body
FROM articles
UNION
SELECT 'reviews', id, title, user_id, created_at, body
FROM reviews
UNION
SELECT 'posts', id, title, user_id, created_at, body
FROM posts

(您只需在第一个查询中定义列别名,它将应用于 UNION 返回的所有行。)

https://laravel.com/docs/5.6/queries#selects显示了选择列表中自定义列的示例

因此您应该能够在字段中定义额外的列:

$common_fields = [
    'id',
    'title',
    'user_id', 
    'created_at',
    'body'
];

$fields = array_merge(["articles as table_name"], $common_fields)
$articles = DB::table('articles')->select($fields);

$fields = array_merge(["reviews"], $common_fields)
$reviews = DB::table('reviews')->select($fields);

$fields = array_merge(["posts"], $common_fields)
$posts = DB::table('posts')->select($fields);

以上我没有测试过。

© www.soinside.com 2019 - 2024. All rights reserved.