Laravel还有一个如何保存ID

时间:2017-03-24 09:21:03

标签: laravel eloquent

我是laravel的新手但我真的很喜欢它。 现在我和Eloquent玩了一点,然后提出了一个问题:

我有两个地址的Cusomers(BillingAdress和DeliveryAddress)

Cusomers-Fields:ID,Firstname,Lastname,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被保存了,但是cusomer表中的deliveryAddress和billingAddress是空的。

1 个答案:

答案 0 :(得分:0)

您应该设置外键和本地键,以便Laravel知道您指的是哪些字段。

class Customer extends Model
{
    public function deliveryAddress() {
        return $this->hasOne("App\Address", "id", "deliveryAddress");
    }

    public function billingAddress() {
        return $this->hasOne("App\Address", "id", "billingAddress");
    }
}

有关如何使用这些内容的完整文档,请访问:https://laravel.com/docs/5.4/eloquent-relationships#one-to-one