Eloquent get only one column as an array

前端 未结 5 2055
时光说笑
时光说笑 2020-12-08 01:39

How to get only one column as one dimentional array in laravel 5.2 using eloquent?

I have tried:

$array = Word_relation::select(\'word_two\')->wh         


        
相关标签:
5条回答
  • 2020-12-08 02:05

    I think you can achieve it by using the below code

    Model::get(['ColumnName'])->toArray();

    0 讨论(0)
  • 2020-12-08 02:06

    You can use the pluck method:

    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.

    0 讨论(0)
  • 2020-12-08 02:07

    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();
    
    0 讨论(0)
  • 2020-12-08 02:14

    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().

    // <= 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

    // <= 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');
    
    0 讨论(0)
  • 2020-12-08 02:22

    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

    if you do

    User::pluck('id') // [1,2,3, ...]
    

    & of course you can have any other clauses like where clause before pluck

    0 讨论(0)
提交回复
热议问题