如何制作虚拟列?

时间:2016-10-26 10:22:41

标签: php mysql sql laravel

这是我的问题:

    $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中做到这一点?

3 个答案:

答案 0 :(得分:2)

您可以使用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();

答案 1 :(得分:1)

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

仅供参考,https://laravel.com/docs/5.3/queries#raw-expressions

答案 2 :(得分:1)

您可以将DB :: raw用于此

 DB::raw('news as tableName')

 DB::raw('productions as tableName')
选择部分

中的