Laravel多对多关系下通过多个Ingrediente id过滤Receita表记录的方法
实现步骤
1. 确认模型关联已定义
首先确保你的Receita模型已经正确配置了和Ingrediente的多对多关联:
// app/Models/Receita.php public function ingredientes() { return $this->belongsToMany(Ingrediente::class); }
2. 修改控制器逻辑
你可以直接修改原有mostrarTodos方法,同时兼容全量展示和筛选场景,不需要单独开发过滤方法:
public function mostrarTodos(\Illuminate\Http\Request $request) { // 获取选中的配料ID数组,默认空数组 $checkedIngredientes = $request->input('ingrediente', []); // 格式化ID并过滤无效值,避免异常 $checkedIngredientes = array_filter(array_map('intval', $checkedIngredientes)); $receitasQuery = Receita::query(); // 只有存在选中配料时才追加筛选条件 if (!empty($checkedIngredientes)) { $receitasQuery->whereHas('ingredientes', function ($query) use ($checkedIngredientes) { $query->whereIn('ingredientes.id', $checkedIngredientes); }, '=', count($checkedIngredientes)); } $receitas = $receitasQuery->get()->toArray(); $ingredientes = Ingrediente::all()->toArray(); return view('home', compact('receitas', 'ingredientes')); }
3. 调整前端表单(可选)
如果要复用原有首页路由,直接把表单的action留空即可,提交后会自动请求当前页面:
<form action="" class="grid grid-cols-4" method="GET">
逻辑说明
whereHas的第三个参数用于限制匹配的关联条目数量,当该数值等于你选中的配料总数时,就代表当前Receita条目包含了所有选中的配料,完全匹配需求。
内容的提问来源于stack exchange,提问作者Gabriel Freitas
相关产品推荐
相关产品推荐

