Eloquent Как хранить данные, если у меня есть 2 модели с «один ко многим» на одной модели? - PullRequest
0 голосов
/ 19 мая 2018

Хорошо, у меня есть следующая диаграмма ER, которая показывает мои отношения в БД: enter image description here Я желаю сгенерировать User, когда будет сделано Order.Order может содержать множество Products, также Orders сгруппированы по их transaction_id, поэтому я могу включить все продукты в том же порядке для пользователя.Я пытаюсь спасти их всех, но я получаю Field 'transaction_id' doesn't have a default value.Мне удалось сохранить пользователя, а также связать заказ с продуктом и пользователем, но я все еще не могу понять, как сохранить транзакцию_id, связанную с заказом.Это мои миграции:

Schema::create('orders', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('user_id')->unsigned()->index()->nullable();
            $table->foreign('user_id')->references('id')->on('users');
            $table->integer('transaction_id')->unsigned();
            $table->foreign('transaction_id')->references('id')->on('transactions');
            $table->timestamps();

Schema::create('order_product', function (Blueprint $table) {
            $table->integer('order_id')->unsigned()->index();
            $table->foreign('order_id')->references('id')->on('orders')->onDelete('cascade');
            $table->integer('product_id')->unsigned()->index();
            $table->foreign('product_id')->references('id')->on('products')->onDelete('cascade');
            $table->integer('quantity')->unsigned();
            $table->timestamps();
        });
Schema::create('products', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->float('price',8,2);
            $table->timestamps();
        });
Schema::create('transactions', function (Blueprint $table) {
            $table->increments('id');
            $table->enum('status',['open','closed']);
            $table->timestamps();
        });

Мои модели:

Модель пользователя:

public function orders() {return $this->hasMany(Order::class);}

Модель заказа:

public function user()
    {
        return $this->belongsTo(User::class);
    }

    public function products()
    {
        return $this->belongsToMany(Product::class)
        ->withPivot('quantity')
        ->withTimestamps();
    }

    public function transaction()
    {
        return $this->belongsTo(Transaction::class);
    }

Модель транзакции:

public function orders() {return $this->hasMany(Order::class);}

Вот как я пытаюсь их спасти:

$user->save();
$transaction->save();
$order = new Order();
$order->user_id = $user->id;
$user->orders()->save($order);
$transaction->orders()->save($order);
$order->products()->attach($cartItem->id, ['quantity' => $cartItem->qty]);

PS Извините за длинный пост, у меня нет идей.

1 Ответ

0 голосов
/ 19 мая 2018

Используйте это:

$order = new Order();
$order->user_id = $user->id;
$order->transaction_id = $transaction->id;
$order->save();
...