Home » Php » php – Select fields from eager loaded model

php – Select fields from eager loaded model

Posted by: admin February 25, 2020 Leave a comment

Questions:

I want to use the select() filter to get columns both from the main Model and the related model, which I’m loading with the with() function, but I haven’t found a general answer on how this should work.
The output of this should be a list which can be loaded in a select2 component.

Let’s say I have two models, Province and Country, and Province has a foreign key on Country (country_id); in the Model this relationship is described with belongsTo (Province->country()) and hasMany (Country->provinces()).
This works, but I don’t like it because it’s not the pure Eloquent solution (the output array is called $data):

    $result = Province::with('country')
    ->where ( 'provinces.name', 'LIKE', '%' . $search . '%' )
    ->limit(25)
    ->get();
    foreach ($result as $res) {
        $data[] = ['id' => $res->id, 'text' => $res->name." - ".$res->country->name];
    }

This works but it creates an array with a nested object for each row

    $result = Province::with('country')
    ->where ( 'provinces.name', 'LIKE', '%' . $search . '%' )
    ->limit(25)
    ->get();

This doesn’t because it can’t find the column country.name

    $result = Province::with('country')
    ->where ( 'provinces.name', 'LIKE', '%' . $search . '%' )
    ->limit(25)
    ->select('provinces.id', DB::raw('CONCAT(provinces.name," ", country.name) AS text'))
    ->get();

I also tried with the select/addSelect in the anonymous function in the with(), as I read in other answers.
What’s the correct way to have the array with the combined fields from the parent and child Model?

Thanks!

How to&Answers: