使用 Laravel 查询构建器的字段常量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16950419/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
field constant using laravel query builder
提问by user1307065
Using laravel/fluent query builder, I'm trying to cause a constant field value to pass through for a union(ed) selection that is subsequently ordered . I haven't found the recipe to do the following with fluent. The unions are easy, but how do you get the field constant to work?
使用 laravel/fluent 查询构建器,我试图通过一个常量字段值传递给随后排序的 union(ed) 选择。我还没有找到用 fluent 做以下事情的秘诀。工会很容易,但你如何让这个领域持续工作?
Imagine two simple tables (omitted) and a union select:
想象两个简单的表(省略)和一个联合选择:
select field1, field2, 'type1' as field3 from table1
UNION
select field1, field2, 'type2' as field3 from table2
ORDER BY field2
The best answer I've come up with so far, is to use a DB::query with a query string I manufacture myself. Laravel/fluent does not seem ready to handle this case, given the test cases I've tried. Using RAW for a select works great, until you try to order the pair of selected table queries.
到目前为止,我想出的最佳答案是将 DB::query 与我自己制造的查询字符串一起使用。鉴于我尝试过的测试用例,Laravel/fluent 似乎还没有准备好处理这种情况。使用 RAW 进行选择效果很好,直到您尝试对这对选定的表查询进行排序。
SELECT field1, field2 FROM
(
SELECT fld1A as field1, 'FOO' as field2 from table1
UNION ALL
SELECT fld2A as field1, 'BAR' as field2 from table2
)
temp_table order by somefield
回答by ClockworkCoder
Using Laravel 4, and using GROUP BY, rather than ORDER BY I believe you can do something like:
使用 Laravel 4,并使用 GROUP BY,而不是 ORDER BY 我相信你可以这样做:
$t1 = DB::table('table1')
->select('field1',DB::raw("'FOO' as field2"))
->groupBy('field2');
$t2 = DB::table('table2')
->select('field1',DB::raw("'BAR' as field2"))
->groupBy('field2');
$result = $t1->union($t2)->get();
I found that $t1
in this case can be an instance of Illuminate\Database\Query\Builder
or Illuminate\Database\Eloquent\Builder
, but the union argument ($t2
) must be of type Illuminate\Database\Query\Builder
.
我发现$t1
在这种情况下可以是Illuminate\Database\Query\Builder
or的实例Illuminate\Database\Eloquent\Builder
,但联合参数 ( $t2
) 必须是类型Illuminate\Database\Query\Builder
。
This means that you may use eager loading with something like:
这意味着您可以将预先加载用于以下内容:
$t1 = MyTableModel::with('table3')->select...
$t1 = MyTableModel::with('table3')->select...
回答by Antonio Carlos Ribeiro
This way, probably:
这样,大概:
$users = DB::table('users')
->select(DB::raw("'FOO' as field2"))
->get();