我的代碼是這樣的:如何在查詢關係存在上添加條件? Laravel 5.3
<?php
public function getFavoriteStore($param = null)
{
$num = 20;
$q = $param['q'];
$location = $param['location'];
$result = $this->store_repository->whereHas('favorites', function ($query) {
$query = $query->where('stores.status', '=', 1)
->where('favorites.favoritable_type', 'like', 'App\\\Models\\\Store');
if(isset($location))
$query = $query->where('stores.address', 'like', "%$location%");
if(isset($q)) {
$query = $query->where(function ($query) use ($q) {
$query->where('stores.name', 'like', "%$q%")
->where('stores.address', 'like', "%$q%", 'or');
});
}
return $query;
})->paginate($num);
return $result;
}
它的工作原理
但是,條件如果(if(isset($location))
& if(isset($q))
)不工作
看來還是有錯
是有誰可以幫助我?
我按照這個教程:https://laravel.com/docs/5.3/eloquent-relationships#querying-relationship-existence
if(isset($ location))&& if(isset($ q)) – geckob
不要忘記將'location'和'q'注入到第一個閉包中 – geckob
@geckob,Ok。謝謝bro –