我正在嘗試向過濾表編寫查詢,但看起來有些不對(duì)勁。 $keyword = "chapel"; $city = $request->get("city"); $price = $request->get("price");首先檢查計(jì)劃表是否為空。然后開始編寫過濾查詢。 $datas = Place::whereHas("plans") ->groupBy("address","place_name") ->when($keyword, function($query, $keyword) { return $query->where("place_name", "LIKE", "%$keyword%"); }) ->when($city, function($query, $city) { return $query->where("city", "LIKE", "%$city%"); })查詢工作到 basic_info 表。但是當(dāng)我$keyword在basic_info表中搜索時(shí),然后會(huì)彈出錯(cuò)誤并說調(diào)用模型 > [App\Model\Place] 上的未定義關(guān)系 [basic_infos]。 //basic info table ->when($keyword, function($query) use ($keyword){ $query->with(["basic_infos" => function($query, $keyword){ return $query->where("basic_info.wedding_style", "LIKE", "%$keyword%"); }]); }) //plan table ->when($price, function($query) use ($price){ $query->with(["basic_infos" => function($query, $price){ return $query->where("plans.plan_price", "<=", $price); }]); }) ->paginate(20); return $datas;但實(shí)際上它是定義的。這是模型放置模型public function basicInfos(){ return $this->hasMany("App\Model\BasicInfo");}基本信息模型public function place(){ return $this->belongsTo("App\Model\Place");}但是在查詢內(nèi)部->when函數(shù)中,當(dāng)我使用->with它時(shí),似乎出現(xiàn)了問題。我想,我在錯(cuò)誤的時(shí)間使用它,否則......同樣的事情肯定也會(huì)發(fā)生在plan表的查詢中......什么是正確的方法?
1 回答

米琪卡哇伊
TA貢獻(xiàn)1998條經(jīng)驗(yàn) 獲得超6個(gè)贊
你有兩個(gè)問題:
您需要使用函數(shù)名稱而不是表名稱來建立關(guān)系。
如果您想使用其他參數(shù)
$query
,請(qǐng)使用use。
->when($keyword, function($query) use ($keyword){
$query->with(["basicInfos" => function($query) use ($keyword){
return $query->where("wedding_style", "LIKE", "%$keyword%");
}]);
})
- 1 回答
- 0 關(guān)注
- 180 瀏覽
添加回答
舉報(bào)
0/150
提交
取消