2017-04-11 27 views
0

我使用Laravel 5.3我該如何使用wherehas和join?

我的代碼是這樣的:

public function getWishlist($param) 
{ 
    $num = 20; 
    $q = $param['q']; 
    $location = $param['location']; 

    $result = $this->product_repository->whereHas('favorites', function ($query) use($q, $location) { 
     $query->where('favorites.user_id', '=', auth()->user()->id) 
       ->where('products.status', '=', 1); 

     if($q) 
      $query->where('products.name', 'like', "%$q%"); 
    }) 
    ->join('stores', 'stores.id', '=', 'products.store_id'); 
    if($location) 
     $result->where('stores.address', 'like', "%$location%"); 

    if($q) 
     $result->where('products.name', 'like', "%$q%") 
       ->where('stores.address', 'like', "%$q%", 'or'); 

    dd($result->toSql()); 
    // ->paginate($num); 

    return $result; 
} 

執行時,結果是空

似乎wherehas和加入不同時工作

有沒有什麼解決辦法解決我的問題?

+0

'加入()'工作正常'whereHas()'。你需要使用'toSql()'方法檢查你的SQL查詢。它可以幫助您調試問題。 –

+0

@Amit Gupta,我試試這個:'dd($ result-> toSql());'。存在錯誤:'Method toSql does not exist.' –

+0

我希望你在調用'paginate()'方法之前嘗試'toSql()'。 –

回答

0

我認爲你可以使用先進的地方

$result = $result->where(function($query) use ($q) { 
     $query->where('products.name', 'like', "%$q%") 
     ->where('stores.address', 'like', "%$q%", 'or'); 
}) 
+0

它不起作用。更新完整的答案 –