2017-02-25 115 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 –