Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

304
Visualizações
Laravel Eloquent - Filter Relationship

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.

over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

If you want to filter the the products to eager load and also filter to load only the product masters that hace those products your query should be like this:


$products = ProductMaster::
with([
 'products' =>
 fn($query) => $query
 ->where('client', $clientCode)
 ->whereIn('brand', $filterBrand)
 ->whereIn('size', $filterSizes)
])
->whereHas('products', 
 fn($query) => $query
 ->where('client', $clientCode)
 ->whereIn('brand', $filterBrand)
 ->whereIn('size', $filterSizes)
)
        ->where('title', 'LIKE', '%' . $request->find . '%')
        ->orderby($order[0], $order[1])
        ->paginate(6)
        ->withQueryString();

You could even pass that query on both with and whereHas functions to a private function inside your controller to keep the clone more clean.

over 4 years ago · Santiago Trujillo Relatório

0

Could you please try this and let me know if its working or not ? And also I think you missed the category filtering in one of the whereIn clause.

$q = ProductMaster::with('products')->where(function($query) use ($filterBrand, $filterCats, $filterSizes, $clientCode) {
     $query->whereHas('products', function($query) use ($filterBrand, $filterCats, $filterSizes, $clientCode) {
        $query->where('client', $clientCode);
        $query->whereIn('brand', $filterBrand);
        $query->whereIn('size', $filterSizes);
        $query->whereIn('category', $filterCats);
    });
 });

 $products = $q->where('title', 'LIKE', '%' . $request->find . '%')
                ->orderby($order[0], $order[1])
                ->paginate(6)
                ->withQueryString();
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda