1

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('App\MedicineWeightage', 'medicine_id');
}
0

1 Answer 1

1

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']);
Sign up to request clarification or add additional context in comments.

7 Comments

still it is empty
$medicines = Medicine::with(['weightages' => function($query) { $query->select('id', 'name', 'medicine_id'); }])->select('id','name', 'description')->get(); this solved my problem
Oh, right. I forgot the id column in the parent query. Mea culpa!
Is the any way I do not send primary and foreign keys? This is API I am creating, which one is best with keys or without keys?
You can remove them from the collection via ->pluck(['name', 'description']). If you don't need them, there's no reason to expose them to the client.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.