【发布时间】:2016-10-26 10:22:40
【问题描述】:
这是我的查询:
$first = DB::table('news')
->select(['id', 'title', 'description', 'imgPath'])
->where(function($query) use ($q) {
$query->where('title', 'like', "$q%")
->orWhere('description', 'like', "$q%");
});
$result = DB::table('productions')
->select(['id', 'title', 'description', 'imgPath'])
->where(function($query) use ($q) {
$query->where('title', 'like', "$q%")
->orWhere('description', 'like', "$q%");
})
->unionAll($first)
->get();
如您所见,我使用了union all,它合并了这两个不同查询的结果。好的,现在我需要知道,每一行(结果表的) 属于哪个表。因此,我需要在select 部分再添加一列并将其设置为默认值。然后使用该值来检测行的表。
在纯 SQL 中可能是这样的:
SELECT 'news' as tableName, col1, col2 FROM news WHERE ...
UNION ALL
SELECT 'productions' as tableName, col1, col2 FROM productions WHERE ...
然后在 PHP 中:
if ( $result['tableName'] == 'news' ) {
// this row belongs to "news" table
} elseif( $result['tableName'] == 'productions' ) {
// this row belongs to "productions" table
}
我如何在 Laravel 中做到这一点?
【问题讨论】: