如何在 Laravel 5.1 中使用 Eloquent 进行原始查询的多重选择
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35310925/
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
How to do a multiple select with raw query using Eloquent in Laravel 5.1
提问by Chey Luna
I made a query which gets all the column data of a table and an additional custom column aliased as 'distance'. Right now the query looks like this:
我做了一个查询,它获取一个表的所有列数据和一个别名为“距离”的附加自定义列。现在查询如下所示:
$restaurants = DB::table(DB::raw('restaurants'))
->select(
'restaurants.id',
'restaurants.name',
'restaurants.about',
'restaurants.contact_details',
'restaurants.address',
'restaurants.city',
'restaurants.lat',
'restaurants.long',
'restaurants.cuisines',
DB::raw(*some computation here* . " as distance")
)
->get();
Basically, my query should look like this in SQL:
基本上,我的查询在 SQL 中应该如下所示:
SELECT *, *some computation here* as distance FROM restaurants
SELECT *, *some computation here* as distance FROM restaurants
Is there a way to simplify this using Eloquent? Right now I need to manually specify all the columns just so I could add the DB::raw select statement.
有没有办法使用 Eloquent 来简化这个过程?现在我需要手动指定所有列,以便我可以添加 DB::raw select 语句。
回答by Roj Vroemen
This should work:
这应该有效:
$restaurants = DB::table('restaurants')
->select(
'restaurants.*',
DB::raw(*some computation here* . " as distance")
)
->get();