Eloquent 如果我有 2 个模型,一个模型上有 "one-to-many",我该如何存储数据?

Eloquent How do I store data if i have 2 models with "one-to-many" on one model?

好的,我有以下 ER 图显示我在数据库中的关系: 我愿意在生成 Order 时生成一个 UserOrder 可以包含许多 ProductsOrders 也按其 transaction_id 分组,因此我可以为用户包含相同订单中的所有产品。我正在尝试将它们全部保存,但我得到 Field 'transaction_id' doesn't have a default value。我已经设法保存了用户,也保存了 link 产品和用户的订单,但我仍然不知道如何保存 transaction_id linked 的订单。 这些是我的迁移:

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

P.S。抱歉了这么久post,我没主意了。

使用这个:

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