@Terroris337

Как получить несколько связей laravel?

Есть таблица промо кодов:
Schema::create('promos', function (Blueprint $table) {
            $table->id();
            $table->string('code')->unique();
            $table->integer('discount')->nullable();
            $table->boolean('delivery_discount')->nullable();
            $table->integer('cur_uses_count')->default(0);
            $table->integer('max_uses_count');
            $table->date('end_date');
            $table->foreignId('product_id')->nullable();

            $table->foreign('product_id')->references('id')->on('products');
            $table->timestamps();
        });


К промо коду привязан продукт, у него есть несколько связей, к примеру продукт - мясо:

Schema::create('products', function (Blueprint $table) {
            $table->engine = 'InnoDB';
            $table->id();
            $table->string('name')->unique();
            $table->string('desc')->nullable();
            $table->string('image');
            $table->integer('price')->unsigned()->nullable();
            $table->integer('proteins')->unsigned()->nullable();
            $table->integer('fats')->unsigned()->nullable();
            $table->integer('energy')->unsigned()->nullable();
            $table->integer('carbo')->unsigned()->nullable();
            $table->boolean('top')->default(0);
            $table->boolean('visibility')->default(1);
            $table->string('mutable_in');
            $table->string('no_mutable_in');
            $table->foreignId('category_id');
            $table->timestamps();

            $table->foreign('category_id')->references('id')->on('categories');
        });


Schema::create('meats', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->integer('price');
            $table->string('category')->default('meat');
            $table->string('desc')->nullable();
            $table->foreignId('product_id');
            $table->timestamps();

            $table->foreign('product_id')->references('id')->on('products')->onDelete('cascade');
        });


Связь один ко многим(у продукта несколько видов мяса, но мясо привязано только к одному продукту).
Пока что составил запрос для получения промо кода с продуктом:

public function promo()
    {
        return $this->hasOne(Promo::class);
    }

public function product()
    {
        return $this->belongsTo(Product::class);
    }


$promo = Promo::with('product')->where('code', 'like', '%' . $request->post('code') . '%')->firstOrFail();


Как получить промо код с продуктом и всеми видами мяса продукта?
  • Вопрос задан
  • 167 просмотров
Решения вопроса 1
@jazzus
Promo::with('product.meats')
Ответ написан
Комментировать
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы