简体   繁体   中英

Get specific column value from MySql in Laravel DB select function

How to I get a specific column value after fetching the results from MySql in Laravel DB select function

Below is my php code.

$list = DB::select('SELECT DISTINCT a.pincode FROM table_name nvs 
        JOIN areas a on nvs.area_id = a.id 
        where nvs.city_id = ?;', [$area_id]);

Below is the results for above query.

[
  {
    "pincode": "560005"
  },
  {
    "pincode": "560006"
  }
]

I need only pincode value not as key value pair. So i tried with the below code.

return array_column($list->toArray(), 'pincode');

It gives Call to a member function toArray() on array .

How can I get only values without using foreach loop.

Answer

I used the below code

$pincode_list = DB::table('table_name as nvs')
            ->join('areas as a', 'nvs.area_id', '=', 'a.id')
            ->select('a.pincode')
            ->where('nvs.city_id', '=', $area_id)
            ->distinct('a.pincode')->pluck('pincode')->toArray();

Result was :

[
    "560067",
    "560035"
]

最好的方法是使用Query Builder或Eloquent并使用它代替get()

->pluck('pincode')->toArray();

I think the query should be like

 $area_ids = DB::table('table_name')
        ->join('areas', 'nvs.area_id', '=', 'table_name.id')
        ->select('table_name.pincode')
        ->where('nvs.city_id', '=', $area_id)
        ->distinct()->get();

and if you are getting it as object and want it to be array you can use toArray() here like $area_ids = $area_ids->toArray(); can you please test it and let me know the new status.

$all_pincodes = array_values ($list);

但是我建议您使用Laravel Eloquent,因为无论如何您都在使用Laravel,因此最好使用内置功能来简化此过程。

Using your variant:

\DB::setFetchMode(\PDO::FETCH_ASSOC);
$data = \DB::select($yourQuery);
$pincodes = array_pluck($data, 'pincode')
\DB::setFetchMode(config('database.fetch')); //return fetch to default

Using more fluent way:

  $pincodes = \DB::table('table')->pluck('pincode')->toArray(); //do not forget about wheres and joins in this query.

I would recommend you second variant because this is more clear way to get result what you need.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM