【发布时间】:2017-08-17 03:53:54
【问题描述】:
我是 laravel 的新手,但我已经很喜欢它了。 现在我用 Eloquent 玩了一点,然后出现了一个问题:
我的客户有两个地址(BillingAdress 和 DeliveryAddress)
客户字段:ID、名字、姓氏、BillingAddress、DeliveryAddress 地址-字段:ID、地址、邮编、城市、国家
现在我想创建客户,在创建他之后,我想为他分配地址。
客户模型:
class Customer extends Model
{
public function deliveryAddress() {
return $this->hasOne("App\Address");
}
public function billingAddress() {
return $this->hasOne("App\Address");
}
}
地址模型:
class Address extends Model
{
public function customer() {
return $this->belongsTo("App\Customer");
}
}
控制器:
$c = new Customer;
$c->Firstname = "John";
$c->Lastname = "Doe";
$c->save();
$billingAddress = new Address;
$billingAddress->address = "Exampleroad 3";
$billingAddress->zip = 11111;
$billingAddress->city = "Examplecity";
$deliveryAddress = new Address;
$deliveryAddress->address = "Doestreed 21";
$deliveryAddress->zip = "44444";
$deliveryAddress->city = "Doedown";
$c->billingAddress()->save($billingAddress);
$c->deliveryAddress()->save($deliveryAddress);
但现在地址表中的 cusomer_id 已保存,但客户表中的 deliveryAddress 和 billingAddress 为空。
【问题讨论】: