Answer the question
In order to leave comments, you need to log in
How to query using 3 tables in Laravel?
There are 3 classes:
class Brand extends Model
{
protected $table = 'brands';
public function categories()
{
return $this->hasMany(Category::class);
}
public function products()
{
return $this->hasManyThrough(Product::class, Category::class);
}
}
class Category extends Model
{
protected $table = 'categories';
public function brand()
{
return $this->belongsTo(Brand::class);
}
public function products()
{
return $this->hasMany(Product::class);
}
}
class Product extends Model
{
protected $table = 'products';
public function category()
{
return $this->belongsTo(Category::class);
}
public function brand()
{
return $this->belongsTo(Brand::class);
}
}
SELECT p.*
FROM products p, categories c, brands b
WHERE p.category_id = c.id
AND c.slug = 'remkomplekty'
AND c.brand_id = b.id
AND b.slug = 'aro'
ORDER BY quantity DESC, CODE
Answer the question
In order to leave comments, you need to log in
One will not work, but one request per table - yes https://laravel.com/docs/5.8/eloquent-relationship...
Try with with as described in Eager Loading: Eager Loading Multiple Relationships
$products = Product::whereHas('category', function ($query) use ($categorySlug, $brandSlug) {
$query->whereHas('brand', function ($query) use ($brandSlug) {
$query->where('slug', $brandSlug);
});
$query->where('slug', $categorySlug);
})
->orderBy('quantity', 'DESC')
->orderBy('code')
->get();
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question