Laravel 5具有类型的同一个表上的多个关系

时间:2018-06-14 08:29:08

标签: laravel relationship laravel-5.6

我有两个型号:User& Address

Address中,有一个type属性,它是一个Enum列,可以设置为SHIPPINGBILLING

User可以在Address类型中设置一个SHIPPING,在BILLING类型中设置一个。{/ p>

关系如下:

public function billingAddr()
{
    return $this->hasOne('App\Models\Address')->where('type', Address::TYPE_BILLING);
}

public function shippingAddr()
{
    return $this->hasOne('App\Models\Address')->where('type', Address::TYPE_SHIPPING);
}

如果我正在检索数据,它可以正常工作:

$billingAddress = $user->billingAddr;

但是,如果我要创建一个新关系,我仍然需要手动插入该类型,有什么方法可以通过该关系创建并且该字段将自动填充?

例如:

// Record should be created with type auto set to BILLING
$user->billingAddr()->create($values);

// Record should be created with type auto set to SHIPPING
$user->shippingAddr()->create($values);

1 个答案:

答案 0 :(得分:0)

您可以在User模型中定义两个函数:

function createBilling($address) {
    $this->billingAddr()->create(['address' => $address, 'type' => 'BILLING']);
}

function createShipping($address) {
    $this->shippingAddr()->create(['address' => $address, 'type' => 'SHIPPING']);
}