我的代码是这样的:
<?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))
&amp; if(isset($q))
)不起作用
似乎还有错误
有没有人可以帮助我?
我遵循本教程:https://laravel.com/docs/5.3/eloquent-relationships#querying-relationship-existence
答案 0 :(得分:2)
您需要在第一个闭包中添加use()
:
public function getFavoriteStore($param = null)
{
$num = 20;
$q = $param['q'];
$location = $param['location'];
$result = $this->store_repository->whereHas('favorites', function ($query) use($q, $location) {
$query->where('stores.status', '=', 1)
->where('favorites.favoritable_type', 'like', 'App\\\Models\\\Store');
if(isset($location))
$query->where('stores.address', 'like', "%$location%");
if(isset($q)) {
$query->where(function ($query) use ($q) {
$query->where('stores.name', 'like', "%$q%")
->where('stores.address', 'like', "%$q%", 'or');
});
}
})->paginate($num);
return $result;
}
并且无需在闭包函数中分配和返回$query
变量。