I have two main models in my Laravel project. ProductMaster is where the main product data is and Product is the model which holds the variation of each product and the price for each client. I am not allowed to change this model, in case you wonder.
My question is how to make a eloquent query to get the ProductMaster data with Products that are filtered by client (and other parameters too). I tried whereHas but it didn't work.
This are my Models:
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class ProductMaster extends Model
{
protected $table = 'product_masters';
protected $primaryKey = 'id';
protected $fillable = ['code','title'];
public function products(){
return $this->hasMany(Product::class,'master_id');
}
}
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use App\Models\ProductMaster;
class Product extends Model
{
protected $table = 'products';
protected $primaryKey = 'id';
protected $fillable = ['sku', 'stock', 'brand', 'size', 'priceList', 'master_id', 'client'];
public function productMaster(){
return $this->belongsTo(ProductMaster::class,'master_id');
}
}
And this is the query I tried to do:
//QUERY WITH FILTERS
$products = ProductMaster::whereHas('products', function($query)
use($filterBrand, $filterCats, $filterSizes, $clientCode)
{
$query->where('client', $clientCode);
$query->whereIn('brand', $filterBrand);
$query->whereIn('size', $filterSizes);
})
->where('title', 'LIKE', '%' . $request->find . '%')
->orderby($order[0], $order[1])
->paginate(6)
->withQueryString();
This query works but I don't get exactly what I need. This gives me all ProductMaster that have products where has that parameters, but in collection $products it puts ALL products that have that master_id and not only the products that has that parameters.
This is the sql:
select * from `product_masters` where exists (select * from `products` where `product_masters`.`id` = `products`.`master_id` and `client` = ? and `products`.`brand` in (?) and `category` in (?) and `client` = ?) and `title` LIKE ? order by `title` asc
Here is some sample data: SQL Fiddle
Anyone can help me? Thanks.