2017-02-25 12 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)))は

に動作しない場合、それは

まだ間違っているようです私を助けることができる人は誰ですか?あなたのようにあなたの最初の閉鎖にuse()を追加する必要が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。ありがとうおかあさん –

答えて

2

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 –

関連する問題