Laravel :: 提取多列
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/49188577/
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 ::pluck multiple columns
提问by Lucentyr
I need to populate a blade format <select>
tag.
我需要填充刀片格式<select>
标签。
I'm aware of the Model::pluck('column1', 'column2')
method to populate a select tag.
我知道Model::pluck('column1', 'column2')
填充选择标签的方法。
But in my case, I have to concatenate two columns , and get the id. something like
但就我而言,我必须连接两列,并获取 id。就像是
Model::pluck('column_1 && column_2', 'id')
Model::pluck('column_1 && column_2', 'id')
Is it possible like that ? If yes, what would be the proper syntax?
有可能吗?如果是,正确的语法是什么?
If not, what would be the best alternative then ?
如果没有,那么最好的选择是什么?
回答by Faraz Irfan
Best solution is to create accessorfunction into your model, let's assume if you want to get full name then you can do like this.
最好的解决方案是在你的模型中创建访问器函数,假设你想获得全名,那么你可以这样做。
public function getFullNameAttribute()
{
return $this->first_name . ' ' . $this->last_name;
}
and you can easily get full name.
您可以轻松获得全名。
$users = User::where('id', 1)->get()->pluck('full_name', 'id');
Eloquent will call getFullNameAttribute
function and get concatenated value.
Eloquent 将调用getFullNameAttribute
函数并获得连接的值。
回答by Alexey Mezenin
You could use selectRaw()
:
你可以使用selectRaw()
:
Model::selectRaw("CONCAT ('column1', 'column2') as columns, id")->pluck('columns', 'id');
Or you could do this manually:
或者您可以手动执行此操作:
$collection = Model::get(['column1', 'column2', 'id']);
foreach ($collection as $item) {
$plucked[$item->id] = $item->column1 . $item->column2;
}
dd($plucked);
回答by kmuenkel
Model results retrieved by the get()
method are just children of the regular Support-Collection class, so you actually get access to all the same goodies. Try this:
该get()
方法检索的模型结果只是常规 Support-Collection 类的子类,因此您实际上可以访问所有相同的好东西。尝试这个:
$eloquentCollection = app(YourModel::class)
->where('field', 'value')
->get(['id', 'column_1', 'column_2']);
$mapped = $eloquentCollection->mapWithKeys(function (YourModel $model) {
return [$model->id => $model->column_1 . $model->column_2];
})
回答by zarpio
Another simple way:
另一种简单的方法:
return User::select(DB::raw('CONCAT(first_name, " - ", last_name) AS full_name, id'))
->pluck('full_name', 'id');