Laravel Eloquent 一个模型和多个模型之间的关系如吗啡?

Laravel Eloquent relationship between one Model and Many Models as MorphOne?

简介:

我有这些表格及其模型:

规则:

这里可以进行两种可能的关系规划:

或反过来:

我的问题:

是否有任何其他关系可以将这 4 个模型绑定在一个类似于多态关系的关系中,但不使用 MorphMany 而是使用MorphOne 奇怪的是,我在 Laravel 的文档中找不到它,尽管该方法本身存在于 Eloquent 关系中。

这个MorphOne多态关系是否可能以及它是如何组成的?

现有代码:

//Address model
public function user(){
    return $this->hasOne(User::class);
}
public function company(){
    return $this->hasOne(Company::class);
}
public function property(){
    return $this->hasOne(Property::class);
}

//User model
public function address(){
    return $this->belongsTo(Address::class);
}

//Company model
public function address(){
    return $this->belongsTo(Address::class);
}
//Property model
public function address(){
    return $this->belongsTo(Address::class);
}

这是一侧 A​​ddressUser[=25 之间的 MorphOne 关系=]公司属性 对方:

class Address extends Model
    public function addressable(){
        return $this->morphTo();
    }       
}

class User extends Model
    public function address(){
        return $this->morphOne(Address::class,'addressable'); //note this is not MorphMany()
    }       
}

class Company extends Model
    public function address(){
        return $this->morphOne(Address::class,'addressable');
    }       
}

class Property extends Model
    public function address(){
        return $this->morphOne(Address::class,'addressable');
    }       
}

然后在 UserController 中类似这样的东西:

$user = User::find(1);

$addressData = [
    'street_name' => '5, Golf street',
    'country_id' => 100, //etc..
];

//to add new address record related to user:
$user->address()->create($addressData);
dd($user->address);

//to update existing address record related to user:
$user->address->update($addressData);
//dd($user->address);