Monday, April 10, 2017

How can I use wherehas and join simultaneously?

I use Laravel 5.3

My code is like this :

public function get($param)
{
    $num = 20;
    $q = $param['q'];
    $location = $param['location'];
    $result = $this->product_repository->whereHas('favorites', function ($query) {
        $query->where('favorites.user_id', '=', auth()->user()->id)
              ->where('products.status', '=', 1)
              ->where('favorites.favoritable_type', 'like', 'App\\\Models\\\Product');
    });
    $result = $result->join('stores', 'stores.id', '=', 'products.store_id');
    if($location)
       $result = $result->where('stores.address', 'like', "%$location%");
    if($q) 
        $result = $result->where('products.name', 'like', "%$q%")
                         ->where('stores.address', 'like', "%$q%", 'or');
    $result = $result->paginate($num);
    return $result;
}

When executed, the result is empty

Seems wherehas and join not work simultaneously

Is there any solution to solve my problem?



via samuel toh

Advertisement