Moauya Meghari
Moauya Meghari

Reputation: 501

get data from multiple relations in laravel eloquent

I have the following tables pharmacies,categories,medicines and I am using laravel

the relations are like this

pharmacy have many medicines and the medicine belongs to one category

the medicines table have pharmacy_id and category_id columns + other columns

I want to show a pharmacy by id and it should return an object of pharmacy with categories, each category have object of medicines in this pharmacy. If there is no medicine in any category, then it should not be returned.

I think its a model relations issue

any idea could be useful

the category model

class Category extends Model
{
    protected $table = 'categories';

    public function pharmacies()
    {
        return $this->belongsToMany(Pharmacy::class, 'pharmacy_category', 'category_id', 'id');
    }

    public function medicines()
    {
        return $this->hasMany(Medicine::class);
    }
}

the pharmacy model

class Pharmacy extends Model
{
    use SoftDeletes;
    protected $table = 'pharmacies';

    protected $appends = ['favourite'];

    public function categories()
    {
        return $this->belongsToMany(Category::class,'pharmacy_category','pharmacy_id','id');
    }

    public function getFavouriteAttribute()
    {
        if (!Auth::check()) {
            return 0;
        }
        return (FavouritePharmacy::where('user_id', Auth::user()->id)->where('pharmacy_id', $this->id)->count() == 1) ? 1 : 0;
    }
}

the medicine model

class Medicine extends Model
{

    protected $appends = ['favourite'];

    public function orders()
    {
        return $this->belongsToMany(Order::class);
    }

    public function getFavouriteAttribute()
    {
        if (!Auth::check()) {
            return 0;
        }
        return (FavouriteMedicine::where('user_id', Auth::user()->id)->where('medicine_id', $this->id)->count() == 1) ? 1 : 0;
    }
}

Upvotes: 2

Views: 2486

Answers (1)

Alexey Mezenin
Alexey Mezenin

Reputation: 163748

If you want to display pharmacy info, categories with medicines, with these relationships I'd do this:

$pharmacy = Pharmacy::find($id);

$categoriesWithMedicines = Category::whereHas('medicines', function($q) use($id) {
        $q->where('pharmacy_id', $id);
    })
    ->with(['medicines' => function($q) use($id) {
        $q->where('pharmacy_id', $id);
    }])
    ->get();

Then in a view, you'll have a pharmacy object and a list of categories with medicines which belong to the pharmacy:

@foreach ($categoriesWithMedicines as $category)
    {{ $category->name }}
    @foreach ($category->medicines as $medicine)
        {{ $medicine->name }}
    @endforeach
@endforeach

Upvotes: 2

Related Questions