如何在Laravel中选择多列

时间:2019-05-02 17:11:49

标签: php laravel eloquent laravel-collection

我想获得一个学生的全名,但是在我的数据库中,我有两个不同的列:first_namelast_name.我想同时获得这两个列。

控制器

public function getStudentName($id) 
{
    $students = DB::table("students")->where("students_class_id", $id)
        ->pluck("first_name", "id");

    return json_encode($students);
}

4 个答案:

答案 0 :(得分:2)

在雄辩的模型中创建自定义访问器,例如:

public function getFullNameAttribute()
{
   return $this->first_name . ' ' . $this->last_name;
}

然后在查询中使用它:

$students = DB::table("students")->where("students_class_id",$id)->pluck("full_name","id");

以雄辩的方式尝试:

Student::where("students_class_id",$id)->pluck("full_name","id")->toArray();

答案 1 :(得分:2)

您可以在雄辩的查询中合并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);
}

答案 2 :(得分:1)

如果要选择多个列,可以根据需要使用onlyexcept

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",
       },
     ],
   }
>>>

答案 3 :(得分:0)

我之前的情况相同,并且已经创建了模型范围

/**
     * 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"
    ]
  ]
}

说明

参数:

  

[第一个参数] $ query这将对所有模型自动分解   范围

     

[第二个参数] $ keyColumn保存ID或主要值的列   键[id]

     

[第三个参数] $ extraFileds列的列表需要删除   [名字,姓氏]

所以现在我们有了数组的键和值

因此,如果您想在同一行中显示名字和姓氏

您可以使用foreachmap

我都测试过,但是foreachmap

foreach($ collection as $ idField => $ columnFilelds)     {

    $fianArray[ $idField] = $columnFilelds[ 'first_name'].'-'.$columnFilelds[ 'last_name'];

}

所以现在dd($fianArray)

array:2 [▼
  2 => "John-Doe"
  3 => "Foo-Bar"
]

希望有帮助

  

一件事,您不仅可以提取多个列   first_name,last_name