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

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

Eloquent get only one column as an array

laraveleloquentlaravel-5.2

提问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 pluckmethod:

您可以使用以下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

If you receive multiple entries the correct method is called lists.

如果您收到多个条目,则正确的方法称为列表

    Word_relation::select('word_two')->where('word_one', $word_id)->lists('word_one')->toArray();

回答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 Usermodel & 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 whereclause 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();