Tuesday, April 11, 2017

How can I use wherehas and join simultaneously?

I use Laravel 5.3

My code is like this :

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;
}

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