laravel - 如何在控制器的关系方法中应用条件?
问题描述
我有三个模型 MainCategory、Subcategory 和 Menu
主要类别型号
protected $table="main_categories";
protected $fillable =['category'];
public function subCategories()
{
return $this->hasMany(SubCategory::class,'maincategory_id');
}
子类别模型
protected $table="sub_categories";
protected $fillable =['category','maincategory_id'];
public function foods()
{
return $this->hasMany(Menu::class,'subcategory_id');
}
菜单模型
protected $table="menus";
protected $fillable = [
'resturant_id',
'maincategory_id',
'subcategory_id',
'foodtype_id',
'food_name',
'slug',
'food_price',
'food_image'
];
public function mainCategory()
{
return $this->belongsTo(MainCategory::class,'maincategory_id');
}
public function subCategory()
{
return $this->belongsTo(SubCategory::class,'subcategory_id');
}
问题出在我的控制器中
$data['main_category'] = MainCategory::with(['subCategories', 'menus'])
->whereHas('subCategories.foods', function ($q) use ($resturantid) {
return $q->where('resturant_id', $resturantid);
})
->whereHas('menus', function ($q) use ($resturantid) {
return $q->where('resturant_id', $resturantid);
})
->get();
我想在子类别foods()
方法中应用条件 where resturant_id
is resturant.id
。但它显示了所有的餐厅数据。我也应用了带有符号的子查询,但没有帮助
解决方案
我不确定这是否是您想要的,但您可以尝试以下方法:
$data['main_category'] = MainCategory::with([
'subCategories.foods' => function ($q) use ($resturantid) {
$q->where('resturant_id', $resturantid);
},
'menus'
])
->whereHas('subCategories.foods', function ($q) use ($resturantid) {
return $q->where('resturant_id', $resturantid);
})
->whereHas('menus', function ($q) use ($resturantid) {
return $q->where('resturant_id', $resturantid);
})
->get();
这只会加载resturant_id
匹配的子类别中的食物$resturantid
推荐阅读
- php - PHP 7 包含文件错误 - 文件名解析不正确
- c# - 格式字符串 {0:d MMM YYYY} 如何工作?
- ffmpeg - 将 ffmpeg 原始数据请求到 mp4 容器示例
- android - 如何在统一的导出项目中添加额外的代码行到 android studio?
- javascript - 将数据从一个数组复制到另一个数组
- c - 使用 Viete 公式逼近 C 中 pi 的值
- google-oauth - Dialogflow API 不记名令牌
- html - 宽度为 100%,但内容仍未填满页面
- c# - 在 RadGrid 中使用 RenderMode 时出现错误
- python - 选择每组的最大值