如何在Laravel模型之间建立正确的关系

时间:2019-02-12 21:23:34

标签: php laravel datatable

因此,我有两个名为“ customers”和“ billing_addresses”的表。 我也有两个名为“客户”和“ BillingAddress”的模型。

在billing_addresses表中,有多个地址,每个地址都有一个“ id”。

在“客户”表中,每个客户都有一个“ billing_address_id”值,该值对应于billing_addresses表中的一项。

到目前为止,我设法创建的是:

// Customer relationship method(in the model file)
   public function address()
{
    return $this->hasOne('App\BillingAddress','id');
}


/////////

// BillingAddress relationship method(in the model file)


 public function customer()
    {
        return $this->hasMany('App\Customer','id');
    }

当我进行类似Customer::with('address');

的操作时,我的确在获取正确的数据

但是我觉得有一个更好的方法,因为我也得到

BadMethodCallException

Call to undefined method 

Illuminate\Database\Eloquent\Relations\HasOne::getForeignKey()  

当我尝试使用数据表进行过滤时(无法确定其是否相关,但首先我想对关系采用最佳方法)。

谢谢!

2 个答案:

答案 0 :(得分:0)

一个自定义可以有多个帐单地址。因此它的客户可以有许多地址,而一个地址属于该客户。

// Customer Model
public function addresses()
{
    return $this->belongsTo('App\BillingAddress', 'customer_id');
}


// BillingAddress Model
public function customer()
{
    return $this->hasMany('App\Customer', 'billing_address_id');
}

然后您可以做:Customer::with('addresses')->get();

第二,确保将正确的外键列作为第二个参数传递给关系方法。请参阅documentation以获取参考

第二个错误可能是由于不正确的外键列作为第二个参数传递而引起的。

答案 1 :(得分:0)

您要实现的目标是:

// Customer Model
public function address()
{
    return $this->belongsTo('App\BillingAddress');
}


// BillingAddress Model
public function customer()
{
    return $this->hasMany('App\Customer');
}

您需要在客户模型上使用belongsTo,因为您在客户表中存储了计费ID。 Eloquent会自动将账单ID与客户模型中的外键匹配。您只需要遵循外来关键字的Eloquente命名约定即可。在这里查看更多信息。

Eloquent Relations