【问题标题】:Laravel hasOne how to save IDLaravel hasOne如何保存ID
【发布时间】: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 为空。

【问题讨论】:

    标签: laravel eloquent


    【解决方案1】:

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

    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

    【讨论】:

    • 好吧,我想我是因为函数名称与列完全一样??现在我更改了函数名称,但数据库中的字段仍然为空
    猜你喜欢
    • 1970-01-01
    • 2016-07-30
    • 2012-08-15
    • 1970-01-01
    • 2012-01-22
    • 2020-10-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多