首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何创建虚拟列?

如何创建虚拟列?
EN

Stack Overflow用户
提问于 2016-10-26 10:22:40
回答 3查看 520关注 0票数 1

以下是我的疑问:

代码语言:javascript
运行
复制
    $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中,它可以是这样的:

代码语言:javascript
运行
复制
SELECT 'news' as tableName, col1, col2 FROM news WHERE ...
UNION ALL
SELECT 'productions' as tableName, col1, col2 FROM productions WHERE ...

然后在PHP中:

代码语言:javascript
运行
复制
if ( $result['tableName'] == 'news' ) {
    // this row belongs to "news" table
} elseif( $result['tableName'] == 'productions' ) { 
    // this row belongs to "productions" table
}

我怎样才能在拉拉维尔做到这一点?

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2016-10-26 10:31:08

您可以使用selectRaw()方法而不是select():

代码语言:javascript
运行
复制
$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();
票数 2
EN

Stack Overflow用户

发布于 2016-10-26 10:27:19

使用Raw Expression ->select(DB::raw('news' as tableName, col1, col2'))

菲伊,https://laravel.com/docs/5.3/queries#raw-expressions

票数 1
EN

Stack Overflow用户

发布于 2016-10-26 10:31:47

可以为此使用DB::raw

代码语言:javascript
运行
复制
 DB::raw('news as tableName')

 DB::raw('productions as tableName')

在选择部分

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/40259702

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档