K
K
kamilqiyasov2020-07-21 08:57:32
MySQL
kamilqiyasov, 2020-07-21 08:57:32

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


I combined them, everything is fine, but how do I make a query with the union of these three tables. So that with one query I pulled all 3 tables and + added a couple of conditions.
The problem is this:
On the page, I need to display products with the category nc which is equal to remkomplekty and with the brand nc = aro

In SQL, I do this:
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


Tell me, what will be the logical and beautiful controller code in the "Laravel Language".

Variants with DB::table, DB::select do not roll.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Anton Anton, 2020-07-21
@Fragster

One will not work, but one request per table - yes https://laravel.com/docs/5.8/eloquent-relationship...

A
Alexey Sundukov, 2020-07-21
@alekciy

Try with with as described in Eager Loading: Eager Loading Multiple Relationships

K
kamilqiyasov, 2020-07-21
@kamilqiyasov

$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();

There is such code, but at $products->category it makes a new request

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question