0
votes

I have two tables: drugs table and formulations table. The drugs table has fields id, name, quantity and formulation_id. The formulations table has fields id and name.

What relationship should I use to get the drugs records including the name of the formulation.

Note that 1 drug record has only one 1 formulation record.

I have tried using hasOne relashionship but doesn't work:

My view looks as follows:

@foreach($drugs as $drug)
        <li>
            <a class="padded-list" href="">{{$drug->name}} ({{$drug->formulation->name}})</a>
        </li>
        @endforeach

My model relationship in the the Drug model looks as follows:

public function formulation()
{
    return $this->hasOne('App\Formulation');
}
2

2 Answers

0
votes

Your formulation() method in your Drug model should be:

public function formulation()
{
    return $this->belongsTo('App\Formulation');
}
0
votes

If you call $drug->formulation return Eloquent Collection, you can't get name

You should call $drug->formulation()->first()->name