laraveleloquentbelongs-to

laravel 6.0 belongsTo with ApplicationService


I'm new in laravel framework. I couldn't get work medicine with prices in controller.

My model;


use Illuminate\Database\Eloquent\Model;

class Medicine extends Model
{
    protected $table    = 'medicine';
    protected $fillable = [];
    protected $guarded  = [];

    public function withPrice()
    {
        return $this->hasMany('App\Models\MedicinePrice', 'medicine_id', 'id');
    }
}

In my app service ;

    public function getRecentEntries()
    {
        $medicines = Medicine::orderBy('id','DESC')->take(10)->get()->toArray();
        dd($medicines);
        return $this->formatMedicine($medicines);
    }

Table of medicine : https://take.ms/EHrwd Table of medicine_price : https://take.ms/BMTJW

Any helps ? Thank you so much.


Solution

  • You are never loading the relationship in your code. You can accomplish it with:

    Medicine::with('withPrice')->get();
    

    However, the with('withPrice') sounds a little weird doesn't it? I would recommend you to rename the method of your relation in your Medicine model to something prettier, like prices:

    public function prices()
    {
        return $this->hasMany(MedicinePrice::class);
    }
    

    And then you can retrieve the medicine with the prices like this:

    $medicines = Medicine::with('prices')->orderByDesc('id')->take(10)->get()->toArray();
    

    You can read more about eager loading here: https://laravel.com/docs/6.x/eloquent-relationships#eager-loading