I want to get specific column from Model relation in Laravel, but the relation model returning empty array.
Eloquent Query
$medicines = Medicine::with(['weightage' => function($query) { $query->select('name'); }])->get(['name', 'description']);
Medicine Modal
public function weightage() { return $this->hasMany('AppMedicineWeightage', 'medicine_id'); }
Advertisement
Answer
You always need to also select the primary and foreign keys of the table to make the relation work:
$medicines = Medicine::with(['weightage' => function($query) { $query->select(['id', 'name', 'medicine_id']); }])->get(['id', 'name', 'description']);