对于很多情况,嗨laravel没有在数据透视表中插入正确的值.
我的第一个模型是
class ShippingAddress extends Eloquent { protected $guarded = array('id'); protected $table = 'shippingAddress'; public function mwsOrder() { return $this->belongsToMany('MwsOrder','mwsOrders_shippingAddress','Address_id','AmazonOrderId' ); } }
第二种模式是
class MwsOrder extends Eloquent { protected $table = 'mwsOrders'; protected $primaryKey = 'AmazonOrderId'; public function shippAddress() { return $this->belongsToMany('ShippingAddress','AmazonOrderId','Address_id' ); } }
EER图
现在,当我运行这个
$mwsOrder = new MwsOrder; $mwsOrder->AmazonOrderId = 'Eve 6'; $mwsOrder->save(); $address = new ShippingAddress; $address->name = 'Naruto Uzumaki'; $address->save(); $address->mwsOrder()->attach($mwsOrder); //$mwsOrder->shippAddress()->save($address);
laravel抛出错误,这就是laravel尝试运行查询的原因
(SQL: insert into
mwsOrders_shippingAddress
(Address_id
,AmazonOrderId
) values (1,3))
我需要的是生成此查询
insert into
mwsOrders_shippingAddress
(Address_id
,‘Eve 6’)
更新:
架构是:
Schema::create("shippingAddress",function(Blueprint $table) { $table->increments("id"); $table->string("Name"); $table->timestamps(); }); Schema::create("mwsOrders",function(Blueprint $table) { $table->increments("id"); $table->string("AmazonOrderId")->unique(); $table->timestamps(); }); Schema::create("mwsOrders_shippingAddress",function(Blueprint $table) { $table->increments("id"); $table->string("AmazonOrderId"); $table->foreign("AmazonOrderId")->references("AmazonOrderId")->on('mwsOrders'); $table->integer("shipping_address_id")->unsigned(); $table->foreign("shipping_address_id")->references('id')->on('shippingAddress'); $table->timestamps(); });
解决方法
首先将shippAddress更改为:
// Specify the primary key because it's not conventional id protected $primaryKey = 'AmazonOrderId'; public function shippAddress() { return $this->belongsToMany('ShippingAddress','Address_id' ); }
然后你可以试试这个:
$mwsOrder = new MwsOrder; $mwsOrder->AmazonOrderId = 'Eve 6'; $mwsOrder->save(); $address = new ShippingAddress(['name' => 'Naruto Uzumaki']); $mwsOrder->shippAddress()->save($address); // Save and Attach