对于很多情况,嗨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',
'mwsOrders_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:插入
mwsOrders_shippingAddress
(Address_id
,AmazonOrderId
)值(1,3))
我需要的是生成此查询
插入
mwsOrders_shippingAddress
(Address_id
,AmazonOrderId
)值(1,' 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();
});
答案 0 :(得分:1)
首先将shippAddress
更改为:
// Specify the primary key because it's not conventional id
protected $primaryKey = 'AmazonOrderId';
public function shippAddress()
{
return $this->belongsToMany('ShippingAddress',
'mwsOrders_shippingAddress',
'AmazonOrderId',
'Address_id'
);
}
然后你可以试试这个:
$mwsOrder = new MwsOrder;
$mwsOrder->AmazonOrderId = 'Eve 6';
$mwsOrder->save();
$address = new ShippingAddress(['name' => 'Naruto Uzumaki']);
$mwsOrder->shippAddress()->save($address); // Save and Attach