Ilan Finkel Ilan Finkel - 1 month ago 15
PHP Question

Laravel 5.3 Eloquent - select from 3 tables

in addition to my last question Laravel 5.3 Eloquent Relationships

i added a new table called Labels and of course create a new model for this table.

Languages

id
name
short_name


Dictionary

id
label_id
value
language_id


Labels

id
label_name


and i have this code:

$lables = Dictionary::whereHas('language', function($query) {
$short_name = basename(__DIR__);
$query->where('short_name', $short_name);
})->pluck('value', 'label_id')->toArray();


I want to pull out the label_name field instead of the label_id

but I dont know how to make this join.

Answer

You may try using join() as

$lables = Dictionary::whereHas('language', function($query) {
                    $query->where('short_name', 'en');
                })
                ->join('labels', 'dictionary.label_id', '=', 'labels.id')
                ->pluck('dictionary.value', 'labels.label_name')
                ->toArray();

I am not 100% sure that will work, but you can give it a shot.