laravel Eloquent 只获取一列作为数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/34912265/
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
Eloquent get only one column as an array
提问by Riiwo
How to get only one column as one dimentional array in laravel 5.2 using eloquent?
如何使用eloquent在laravel 5.2中仅将一列作为一维数组?
I have tried:
我试过了:
$array = Word_relation::select('word_two')->where('word_one', $word_id)->get()->toArray();
but this one gives it as 2 dimentional array like:
但这个给它作为 2 维数组,如:
array(2) {
[0]=>
array(1) {
["word_one"]=>
int(2)
}
[1]=>
array(1) {
["word_one"]=>
int(3)
}
}
but I want to get it as:
但我想把它作为:
array(2) {
[0]=>2
[1]=>3
}
回答by Bogdan
You can use the pluck
method:
您可以使用以下pluck
方法:
Word_relation::where('word_one', $word_id)->pluck('word_two')->toArray();
For more info on what methods are available for using with collection, you can you can check out the Laravel Documentation.
有关可用于集合的方法的更多信息,您可以查看Laravel 文档。
回答by moxx
回答by SamBremner
I came across this question and thought I would clarify that the lists() method of a eloquent builder object was depreciated in Laravel 5.2 and replaced with pluck().
我遇到了这个问题,我想我会澄清一个 eloquent builder 对象的 list() 方法在 Laravel 5.2 中被贬低并替换为 pluck()。
// <= Laravel 5.1
Word_relation::where('word_one', $word_id)->lists('word_one')->toArray();
// >= Laravel 5.2
Word_relation::where('word_one', $word_id)->pluck('word_one')->toArray();
These methods can also be called on a Collection for example
例如,这些方法也可以在 Collection 上调用
// <= Laravel 5.1
$collection = Word_relation::where('word_one', $word_id)->get();
$array = $collection->lists('word_one');
// >= Laravel 5.2
$collection = Word_relation::where('word_one', $word_id)->get();
$array = $collection->pluck('word_one');
回答by APu
That can be done in short as:
这可以简而言之:
Model::pluck('column')
where model is the Model such as User
model & column as column name like id
其中模型是模型,例如User
模型和列作为列名称,例如id
if you do
如果你这样做
User::pluck('id') // [1,2,3, ...]
& of course you can have any other clauses like where
clause before pluck
& 当然你可以有任何其他条款,比如where
在 pluck 之前的条款
回答by saeid
I think you can achieve it by using the below code
我认为您可以通过使用以下代码来实现它
Model::get(['ColumnName'])->toArray();
Model::get(['ColumnName'])->toArray();