Laravel 5 查询生成器中的多个 select()
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/33472583/
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
Laravel 5 multiple select() in query builder
提问by michael
In laravel 5.1, I want to do like
在 Laravel 5.1 中,我想做
$myTable = MyTable->select('firstField');
if ($somethingTrue) {
$myTable->select('secondField');
}
$myTable->get();
where I want both firstField & secondField to be selected.
Of course the code above is not working, i.e. only the secondField is selected in the end.
Is there any function provided by query builder class that can do exactly what I want?
我希望 firstField 和 secondField 都被选中。
当然上面的代码不起作用,即最后只选择了第二个字段。
查询生成器类提供的任何功能是否可以完全满足我的要求?
回答by Jessedc
Yes, you can use addSelect()
是的,你可以使用 addSelect()
From the Query Builder documentation under "Selects":
If you already have a query builder instance and you wish to add a column to its existing select clause, you may use the addSelect method:
如果您已经有一个查询构建器实例,并且您希望将一列添加到其现有的 select 子句中,您可以使用 addSelect 方法:
$query = DB::table('users')->select('name');
$users = $query->addSelect('age')->get();
Additionally, the API documentation(as apposed to the written documentation) can also shed additional light on what functions are available on core classes.
此外,API 文档(与书面文档并列)还可以进一步阐明核心类上可用的函数。
回答by mwallisch
Accepted answer is probably more elegant, but you could also just use an array of fields for your select clause.
接受的答案可能更优雅,但您也可以只为 select 子句使用一组字段。
$fields = ['firstField'];
if ($someCondition) {
$fields[] = 'secondField';
}
$result = DB::table('users')->select($fields)->get();
回答by Learner
mwallisch's answer is better than accepted one because, if you have multiple places where you are defining selects then addSelect
wont work.
mwallisch 的答案比接受的答案要好,因为,如果您有多个定义选择的地方,则将addSelect
无法使用。
For instance, following code will throw error:
例如,以下代码将抛出错误:
$myTable = MyTable->select('firstField');
if ($somethingTrue) {
$myTable->addSelect('secondField');
}
if ($somethingElseTrue) {
$myTable->addSelect('thirdField');
}
$myTable->get();
while it can be done as:
虽然可以这样做:
$fields = ['firstField'];
if ($somethingTrue) {
$fields[] = 'secondField';
}
if ($somethingElseTrue) {
$fields[] = 'thirdField';
}
$result = DB::table('users')->select($fields)->get();