get data from multiple relations in laravel eloquent
我有以下表格
关系是这样的
药店有很多药品,药品属于一类
我想按 id 显示一个药房,它应该返回一个带有类别的药房对象,每个类别都有这个药房中的药品对象。如果没有任何类别的药品,则不应退货。
我认为这是一个模型关系问题
任何想法都可能有用
类别模型
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | 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); } } |
药房模式
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | 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; } } |
医学模型
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | 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; } } |
如果您想显示药房信息、药物类别以及这些关系,我会这样做:
1 2 3 4 5 6 7 8 9 | $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(); |
然后在一个视图中,您将拥有一个药房对象和一个包含属于该药房的药品的类别列表:
1 2 3 4 5 6 | @foreach ($categoriesWithMedicines as $category) {{ $category->name }} @foreach ($category->medicines as $medicine) {{ $medicine->name }} @endforeach @endforeach |