Reputation: 670
I am trying to write queries to filtering tables, but it's looks like something is not right.
$keyword = "chapel";
$city = $request->get("city");
$price = $request->get("price");
First checking the plans table empty or not. Then start to write filtering queries.
$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%");
})
The queries working till basic_info table. But when I when search $keyword
in basic_info
table then then error pops and says
Call to undefined relationship [basic_infos] on model > [App\Model\Place].
//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;
But actually it's defined. Here is the models
Place Model
public function basicInfos()
{
return $this->hasMany("App\Model\BasicInfo");
}
BasicInfo Model
public function place()
{
return $this->belongsTo("App\Model\Place");
}
But in query inside ->when
function, when I use ->with
it seems, there is a problem happening. I guess, I am using it at wrong time or else... Same thing surely will happen to plan
table's query too.. What is the right way to do it?
Upvotes: 0
Views: 605
Reputation: 13394
You have two problems:
You need to use your function name instead of table name for relationship.
If you want to use another params except $query
, use use.
->when($keyword, function($query) use ($keyword){
$query->with(["basicInfos" => function($query) use ($keyword){
return $query->where("wedding_style", "LIKE", "%$keyword%");
}]);
})
Upvotes: 1