Как собрать несколько столбцов в Laravel - PullRequest
1 голос
/ 02 мая 2019

Я хочу получить полное имя студента, но в моей базе данных у меня есть два разных столбца: 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);
}

Ответы [ 4 ]

2 голосов
/ 02 мая 2019

Вы можете объединить столбцы 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 голосов
/ 02 мая 2019

Создайте пользовательский аксессор в вашей красноречивой модели, например:

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 голос
/ 02 мая 2019

Если вы хотите выбрать несколько столбцов, вы можете использовать либо only или except, в зависимости от ваших требований.

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

    return json_encode($students);
}

In tinker

>>> DB::table('users')->where('id', 1)->select('name', 'email')->get()
=> Illuminate\Support\Collection {#3116
     all: [
       {#3117
         +"name": "superadmin",
         +"email": "superadmin@charmboard.com",
       },
     ],
   }
>>>
0 голосов
/ 03 мая 2019

У меня такая же ситуация и раньше, и я создал область действия модели

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

Explaination

Аргументы:

[Первый аргумент] $ query Это будет автоматически загружено для всех моделей Области применения

[Второй аргумент] $ keyColumn Столбец, содержащий идентификатор или основной ключ [id]

[Третий аргумент] $ extraFileds Список столбцов нужно выщипывать [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"
]

Надеюсь, это поможет

И ОДНА БОЛЬШЕ, ЧТО ВЫ МОЖЕТЕ ПОДКЛЮЧИТЬ НЕСКОЛЬКО КОЛОНН, НЕ ТОЛЬКО first_name,last_name

...