2017-02-25 124 views
0

我的代码是这样的:如何在查询关系存在上添加条件? 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

+0

if(isset($ location))&& if(isset($ q)) – geckob

+1

不要忘记将'location'和'q'注入到第一个闭包中 – geckob

+0

@geckob,Ok。谢谢bro –

回答

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变量。

+0

太好了。有用。谢谢 –

+0

我需要你帮忙。看看这个:http://stackoverflow.com/questions/43630043/why-wheredate-not-working-in-laravel-5-3 –