Laravel 嵌套预加载如何使用 eloquent where condition from inside with nested

Laravel Nested Eager Loading how to use eloquent where condition from inside with nested

我正在寻找一种方法来在我的 laravel eloquent 关系中使用 where 条件与预加载。

这是我的代码

  $data = Model::with(['stage_chatbot'=> function($stage_chatbot){
     $stage_chatbot->select('id', 'customer_id','stage','created_at');
     $stage_chatbot->orderBy('id', 'asc');
  }])->whereIn('hot_leads_id', $getMaxHl)->orderBy('updated_at', 'desc');

  $data->where('stage_chatbot.stage', 'like', 'sampleValue')->get();
  return $data;

谢谢!

试试这个

在 laravel

中使用 use 关键字
$searchText = "sampleValue";
$data = Model::with(['stage_chatbot'=> function($stage_chatbot) use ($searchText) {
        $stage_chatbot->select('id', 'customer_id','stage','created_at')
        ->where('stage_chatbot.stage', 'like', "%".$searchText."%")
        ->orderBy('id', 'asc');
}])->whereIn('hot_leads_id', $getMaxHl)->orderBy('updated_at', 'desc')->get();

有关如何在匿名函数中使用 use 关键字的更多信息 see

您可以像这样使用 whereHas() eloquent 方法。

$data = Model::with(['stage_chatbot'=> function($stage_chatbot){
    $stage_chatbot->select('id', 'customer_id','stage','created_at');
    $stage_chatbot->orderBy('id', 'asc');
}])->whereIn('hot_leads_id', $getMaxHl)->orderBy('updated_at', 'desc');

$data->whereHas('stage_chatbot', function ($stage_chatbot) {
   $stage_chatbot->where('stage', 'like', 'sampleValue')
})->get();
return $data;

在您的搜索输入字段或值上定义一个变量,并通过在您的模型查询中使用传递它

试试这个

$search = $request->search;
$data = Model::with(['stage_chatbot'=> function($stage_chatbot) use ($search) {
    $stage_chatbot->select('id', 'customer_id','stage','created_at');
    $stage_chatbot->where('stage', 'like',$searchText);
    $stage_chatbot->orderBy('id', 'asc');
}])->whereIn('hot_leads_id', $getMaxHl)->orderBy('updated_at', 'desc')->get();