X
X
xnkka2019-12-09 13:49:17
Laravel
xnkka, 2019-12-09 13:49:17

How to specify fields to fetch in eloquent eager loading?

This query works fine, but returns all the fields from both tables,

$cities = City::with(['city_translates'=>function($query) use ($lang_id){
            $query->where('language_id',$lang_id);
        }])
        ->get()
        ->toJson();

if you specify this, then nothing comes from the city_translates table
$cities = City::with(['city_translates'=>function($query) use ($lang_id){
            $query
                ->select('name')
                ->where('language_id',$lang_id);
        }])
        ->get()
        ->toJson();

In this case, it returns the fields of the City table only.
$cities = City::with(['city_translates' => function ($query) use ($lang_id) {
            $query
                ->where('language_id', $lang_id);
        }])
            ->select('name')
            ->get()
            ->toJson();

How to specify the fields for selection and how to properly generate data during eager loading if laravel is used as an api and should return json?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
N
NubasLol, 2019-12-09
@xnkka

$query
                ->select('name')
                ->where('language_id',$lang_id);

Of course, that won't work. For how do you think Lara will have to guess how city_translates and City are connected if you threw out the binding key from the select?
If you want to hide data in json then there is a hidden attribute for that. But!! This is an inherently bad path, and cancerous code.
Especially for you, the developers have made a special tool.
https://laravel.com/docs/6.x/eloquent-resources

M
metallix, 2019-12-09
@metallix

Get Specific Columns Using "With()" Function in La...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question