Laravel 3 Eloquent 如何选择列作为

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18621243/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 08:22:52  来源:igfitidea点击:

Laravel 3 Eloquent How to select column as

selectlaravelaliaseloquentlaravel-3

提问by darksoulsong

I'm trying to figure out how to give a column an alias using Eloquent.

我想弄清楚如何使用 Eloquent 为列指定别名。

So, in other words, how do I execute the following mysql query using Eloquent?

那么,换句话说,我如何使用 Eloquent 执行以下 mysql 查询?

SELECT occupation AS test FROM users WHERE occupation = 'PIMP';

Thx in adv!

谢谢!

回答by amosmos

Eloquent returns a regular Fluent query. So you can try something like this (assuming your model name is 'User'):

Eloquent 返回一个常规的 Fluent 查询。所以你可以尝试这样的事情(假设你的模型名称是“用户”):

$user = User::where_occupation('pimp')->get(array('occupation as test'));

回答by G-Man

This is how I have been able to do this in Laravel 5 using select()and passing the col name and the alias to that method (here I'm also using groupby()to restrict it to "DISTINCT" return values then using toarray()to return any array instead of a Collection Object:

这就是我在 Laravel 5 中使用select()col 名称和别名并将其传递给该方法的方式(在这里我还使用groupby()将其限制为 " DISTINCT" 返回值,然后使用toarray()返回任何数组而不是 a Collection Object

$results = asset::select('model_code__c AS option')->whereRAW("model_code__c <> '' AND status = 'A'")->groupby('model_code__c')->get()->toarray();