【问题标题】:How can I make a virtual column?如何制作虚拟列?
【发布时间】: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 中做到这一点?

【问题讨论】:

    标签: php mysql sql laravel


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

        【解决方案3】:

        您可以为此使用 DB::raw

         DB::raw('news as tableName')
        
         DB::raw('productions as tableName')
        

        在选择部分

        【讨论】:

          猜你喜欢
          • 2011-07-08
          • 1970-01-01
          • 2020-12-08
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-02-11
          相关资源
          最近更新 更多