以下是我的疑问:
$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
}
我怎样才能在拉拉维尔做到这一点?
发布于 2016-10-26 10:31:08
您可以使用selectRaw()方法而不是select():
$first = DB::table('news')
->selectRaw('"news" as tableName, id, title, description, imgPath')
->where(function($query) use ($q) {
$query->where('title', 'like', "$q%")
->orWhere('description', 'like', "$q%");
});
$result = DB::table('productions')
->selectRaw('"productions" as tableName, id, title, description, imgPath')
->where(function($query) use ($q) {
$query->where('title', 'like', "$q%")
->orWhere('description', 'like', "$q%");
})
->unionAll($first)
->get();
发布于 2016-10-26 10:27:19
使用Raw Expression
->select(DB::raw('news' as tableName, col1, col2'))
发布于 2016-10-26 10:31:47
可以为此使用DB::raw
DB::raw('news as tableName')
DB::raw('productions as tableName')
在选择部分
https://stackoverflow.com/questions/40259702
复制相似问题