如何在 Laravel 中提取多列
How to pluck multiple columns in Laravel
我想获取学生的全名,但在我的数据库中,我有两个不同的列:first_name
和 last_name.
我想同时获取这两列。
控制器
public function getStudentName($id)
{
$students = DB::table("students")->where("students_class_id", $id)
->pluck("first_name", "id");
return json_encode($students);
}
在您的 eloquent 模型中创建自定义访问器,例如:
public function getFullNameAttribute()
{
return $this->first_name . ' ' . $this->last_name;
}
然后在查询中使用它,例如:
$students = DB::table("students")->where("students_class_id",$id)->pluck("full_name","id");
用 eloquent 试一下:
Student::where("students_class_id",$id)->pluck("full_name","id")->toArray();
如果您想选择多列,可以使用 only
或 except
,具体取决于您的要求。
public function getStudentName($id)
{
$students = DB::table("students")->where("students_class_id", $id)->select("first_name", "id")->get();
return json_encode($students);
}
正在修补中
>>> DB::table('users')->where('id', 1)->select('name', 'email')->get()
=> Illuminate\Support\Collection {#3116
all: [
{#3117
+"name": "superadmin",
+"email": "superadmin@charmboard.com",
},
],
}
>>>
您可以在 eloquent 查询中连接 first_name 和 last_name 列来解决问题。
public function getStudentName($id)
{
$students = DB::table("students")
->select("id", DB::raw("CONCAT(first_name, ' ', last_name) as name"))
->where("students_class_id", $id)
->pluck("name", "id");
return json_encode($students);
}
我以前遇到过同样的情况,我已经创建了模型范围
/**
* Scope a query to Pluck The Multiple Columns
*
* This is Used to Pluck the multiple Columns in the table based
* on the existing query builder instance
*
* @author Manojkiran.A <manojkiran10031998@gmail.com>
* @version 0.0.2
* @param \Illuminate\Database\Eloquent\Builder $query
* @param string $keyColumn the columns Which is used to set the key of array
* @param array $extraFileds the list of columns that need to plucked in the table
* @return \Illuminate\Support\Collection
* @throws Illuminate\Database\QueryException
**/
public function scopePluckMultiple($query, string $keyColumn, array $extraFileds): \Illuminate\Support\Collection
{
//pluck all the id based on the query builder instance class
$keyColumnPluck = $query->pluck($keyColumn)->toArray();
//start @deprecated because slower than foreach
//anonymous callback method to iterate over the each fileds of table
// $callBcakMethod = function ($eachValue) use ($query) {
// $eachQuery[$eachValue] = $query->pluck($eachValue)->toArray();
// return $eachQuery;
// };
//now we are collapsing the array single time to get the propered array
// $extraFields = Arr::collapse(array_map($callBcakMethod, $extraFileds));
//end @deprecated because slower than foreach
//iterating Through All Other Fileds and Plucking it each Time
foreach ((array)$extraFileds as $eachFiled) {
$extraFields[$eachFiled] = $query->pluck($eachFiled)->toArray();
}
//now we are done with plucking the Required Columns
//we need to map all the values to each key
//get all the keys of extra fileds and sets as array key or index
$arrayKeys = array_keys($extraFields);
//get all the extra fileds array and mapping it to eack key
$arrayValues = array_map(
function ($value) use ($arrayKeys) {
return array_combine($arrayKeys, $value);
},
call_user_func_array('array_map', array_merge(
array(function () {
return func_get_args();
}),
$extraFields
))
);
//now we are done with the array now Convert it to Collection
return new \Illuminate\Support\Collection(array_combine($keyColumnPluck, $arrayValues));
}
因此将其粘贴到您的模型中
$whereCondition = [ ['students_class_id','=',$id] ];
$collection = Student::where($whereCondition )->pluckMultiple('id',['first_name','last_name']);
dd($collection);
结果将是
Collection {#74 ▼
#items: array:1 [▼
2 => array:2 [▼
"last_name" => "Doe"
"first_name" => "John"
]
]
}
说明
参数:
[First Argument] $query This Will be autoloded for all the model
Scopes
[Second Argument] $keyColumn The Column That Hold the Id or primary
key [id]
[Third Argument] $extraFileds The List of Columns needs to be plucked
[first_name,last_name]
所以现在我们得到了数组的键和值
所以如果你想在同一行显示名字和姓氏
您可以使用 foreach
或 map
我都测试过,但是 foreach
比 map
快
foreach($collection as $idField => $columnFilelds)
{
$fianArray[ $idField] = $columnFilelds[ 'first_name'].'-'.$columnFilelds[ 'last_name'];
}
所以现在dd($fianArray)
array:2 [▼
2 => "John-Doe"
3 => "Foo-Bar"
]
希望对您有所帮助
AND ONE MORE THING YOU CAN PLUCK MULTIPLE COLUMNS NOT ONLY THE
first_name,last_name
我想获取学生的全名,但在我的数据库中,我有两个不同的列:first_name
和 last_name.
我想同时获取这两列。
控制器
public function getStudentName($id)
{
$students = DB::table("students")->where("students_class_id", $id)
->pluck("first_name", "id");
return json_encode($students);
}
在您的 eloquent 模型中创建自定义访问器,例如:
public function getFullNameAttribute()
{
return $this->first_name . ' ' . $this->last_name;
}
然后在查询中使用它,例如:
$students = DB::table("students")->where("students_class_id",$id)->pluck("full_name","id");
用 eloquent 试一下:
Student::where("students_class_id",$id)->pluck("full_name","id")->toArray();
如果您想选择多列,可以使用 only
或 except
,具体取决于您的要求。
public function getStudentName($id)
{
$students = DB::table("students")->where("students_class_id", $id)->select("first_name", "id")->get();
return json_encode($students);
}
正在修补中
>>> DB::table('users')->where('id', 1)->select('name', 'email')->get()
=> Illuminate\Support\Collection {#3116
all: [
{#3117
+"name": "superadmin",
+"email": "superadmin@charmboard.com",
},
],
}
>>>
您可以在 eloquent 查询中连接 first_name 和 last_name 列来解决问题。
public function getStudentName($id)
{
$students = DB::table("students")
->select("id", DB::raw("CONCAT(first_name, ' ', last_name) as name"))
->where("students_class_id", $id)
->pluck("name", "id");
return json_encode($students);
}
我以前遇到过同样的情况,我已经创建了模型范围
/**
* Scope a query to Pluck The Multiple Columns
*
* This is Used to Pluck the multiple Columns in the table based
* on the existing query builder instance
*
* @author Manojkiran.A <manojkiran10031998@gmail.com>
* @version 0.0.2
* @param \Illuminate\Database\Eloquent\Builder $query
* @param string $keyColumn the columns Which is used to set the key of array
* @param array $extraFileds the list of columns that need to plucked in the table
* @return \Illuminate\Support\Collection
* @throws Illuminate\Database\QueryException
**/
public function scopePluckMultiple($query, string $keyColumn, array $extraFileds): \Illuminate\Support\Collection
{
//pluck all the id based on the query builder instance class
$keyColumnPluck = $query->pluck($keyColumn)->toArray();
//start @deprecated because slower than foreach
//anonymous callback method to iterate over the each fileds of table
// $callBcakMethod = function ($eachValue) use ($query) {
// $eachQuery[$eachValue] = $query->pluck($eachValue)->toArray();
// return $eachQuery;
// };
//now we are collapsing the array single time to get the propered array
// $extraFields = Arr::collapse(array_map($callBcakMethod, $extraFileds));
//end @deprecated because slower than foreach
//iterating Through All Other Fileds and Plucking it each Time
foreach ((array)$extraFileds as $eachFiled) {
$extraFields[$eachFiled] = $query->pluck($eachFiled)->toArray();
}
//now we are done with plucking the Required Columns
//we need to map all the values to each key
//get all the keys of extra fileds and sets as array key or index
$arrayKeys = array_keys($extraFields);
//get all the extra fileds array and mapping it to eack key
$arrayValues = array_map(
function ($value) use ($arrayKeys) {
return array_combine($arrayKeys, $value);
},
call_user_func_array('array_map', array_merge(
array(function () {
return func_get_args();
}),
$extraFields
))
);
//now we are done with the array now Convert it to Collection
return new \Illuminate\Support\Collection(array_combine($keyColumnPluck, $arrayValues));
}
因此将其粘贴到您的模型中
$whereCondition = [ ['students_class_id','=',$id] ];
$collection = Student::where($whereCondition )->pluckMultiple('id',['first_name','last_name']);
dd($collection);
结果将是
Collection {#74 ▼
#items: array:1 [▼
2 => array:2 [▼
"last_name" => "Doe"
"first_name" => "John"
]
]
}
说明
参数:
[First Argument] $query This Will be autoloded for all the model Scopes
[Second Argument] $keyColumn The Column That Hold the Id or primary key [id]
[Third Argument] $extraFileds The List of Columns needs to be plucked [first_name,last_name]
所以现在我们得到了数组的键和值
所以如果你想在同一行显示名字和姓氏
您可以使用 foreach
或 map
我都测试过,但是 foreach
比 map
foreach($collection as $idField => $columnFilelds) {
$fianArray[ $idField] = $columnFilelds[ 'first_name'].'-'.$columnFilelds[ 'last_name'];
}
所以现在dd($fianArray)
array:2 [▼
2 => "John-Doe"
3 => "Foo-Bar"
]
希望对您有所帮助
AND ONE MORE THING YOU CAN PLUCK MULTIPLE COLUMNS NOT ONLY THE
first_name,last_name