如何在查询关系是否存在时添加条件? Laravel 5.3

How to add condition on Querying Relationship Existence? 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 ( if(isset($location)) & if(isset($q)) ) 不起作用

好像还有错

有没有人可以帮助我?

我遵循这个教程:https://laravel.com/docs/5.3/eloquent-relationships#querying-relationship-existence

您需要在第一个闭包中添加 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;
}

并且不需要在闭包函数中分配 return $query 变量。