Eloquent如果我在一个型号上有两个“一对多”型号,我该如何存储数据?

时间:2018-05-18 22:52:23

标签: php laravel-5 database-design eloquent relational-database

好的,我有以下ER图表显示我在DB中的关系: enter image description here 我愿意在制作zips时生成UserOrder可以包含多个OrderProducts也按Orders分组,因此我可以为用户包含相同顺序的所有产品。我试图将它们全部保存,但我得到了transaction_id。我已设法保存用户,也将产品和用户的订单链接起来,但我仍然无法弄清楚如何保存与订单链接的transaction_id。 这些是我的迁移:

Field 'transaction_id' doesn't have a default value

我的模特:

用户模型:

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

P.S。对不起,很长的帖子,我没有想法。

1 个答案:

答案 0 :(得分:1)

使用此:

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