2017-03-28 32 views
1

我有以下表pharmacies,categories,medicines,我使用laravel得到laravel雄辩从多个关系数据

的关系都是这样

药房有许多药物和药属于一个类别

medicines表具有pharmacy_idcategory_id和列+其它列

我想通过id显示一家药房,它应该返回药房的一个对象类别,每个类别都有药品对象。如果没有任何类别的药品,则不应退货。

我认为它的模型关系问题

任何想法可能是有用的

类型模型

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); 
    } 
} 

药店模型

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; 
    } 
} 

的医学模式

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; 
    } 
} 
+0

您是否有密码? – Laerte

+0

你的问题应该至少表现出最小的努力来接收答复。在这种情况下,它不会。请向我们展示您尝试实现此目的和任何相关错误。 – Ohgodwhy

+0

我更新了问题 –

回答

1

如果你想显示药店信息,类别,有药品,这些关系我会做这样的:在一个视图

$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(); 

然后,你将有一个药店对象和类别的一个列表属于药房的药品:

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

谢谢,它的工作 –

+0

我确实批准了它 –