首页 > 解决方案 > 如何在控制器的关系方法中应用条件?

问题描述

我有三个模型 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_idis resturant.id。但它显示了所有的餐厅数据。我也应用了带有符号的子查询,但没有帮助

标签: laraveleloquent

解决方案


我不确定这是否是您想要的,但您可以尝试以下方法:

$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


推荐阅读