【发布时间】:2018-10-29 10:01:51
【问题描述】:
好的,我有以下 ER 图,显示了我在 DB 中的关系:
我愿意在生成Order 时生成User。 Order 可以包含许多Products,Orders 也按其transaction_id 分组,因此我可以将所有产品包含在同一用户的同一顺序中。我正在尝试将它们全部保存,但我得到了Field 'transaction_id' doesn't have a default value。我设法保存了用户,也将订单与产品和用户联系起来,但我仍然不知道如何保存与订单相关联的 transaction_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]);
附:抱歉,帖子太长了,我没有主意。
【问题讨论】:
标签: php laravel-5 database-design eloquent relational-database