[英]Get specific column value from MySql in Laravel DB select function
在Laravel DB select函數中從MySql獲取結果后如何獲取特定的列值
下面是我的PHP代碼。
$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]);
以下是上述查詢的結果。
[
{
"pincode": "560005"
},
{
"pincode": "560006"
}
]
我只需要pincode值而不是鍵值對。 所以我嘗試了下面的代碼。
return array_column($list->toArray(), 'pincode');
它給array的成員函數toArray()提供了Call 。
如何不使用foreach循環而僅獲取值。
回答
我用下面的代碼
$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();
結果是:
[
"560067",
"560035"
]
最好的方法是使用Query Builder或Eloquent並使用它代替get()
:
->pluck('pincode')->toArray();
我認為查詢應該像
$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();
如果您將其作為對象並希望將其作為數組,則可以在此處使用toArray()
,例如$area_ids = $area_ids->toArray();
能否請您測試一下並讓我知道新狀態。
$all_pincodes = array_values ($list);
但是我建議您使用Laravel Eloquent,因為無論如何您都在使用Laravel,因此最好使用內置功能來簡化此過程。
使用您的變體:
\DB::setFetchMode(\PDO::FETCH_ASSOC);
$data = \DB::select($yourQuery);
$pincodes = array_pluck($data, 'pincode')
\DB::setFetchMode(config('database.fetch')); //return fetch to default
使用更流暢的方法:
$pincodes = \DB::table('table')->pluck('pincode')->toArray(); //do not forget about wheres and joins in this query.
我建議您使用第二個變體,因為這是獲得所需結果的更清晰方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.