问题描述
我正在尝试设置一个多态的一对一关系(多态等效的has_one和belongs_to)。我有一个地址
模型,那里是其他几个我想要一个地址的模型。但是,我对文档的措辞感到困惑。我看过 morphMany
方法,但我的问题是:我应该使用 morphMany
,即使我只想有一个地址,还是有什么东西像 morphOne
方法我应该使用?
I'm trying to setup a polymorphic one-to-one relationship (the polymorphic equivalent of has_one and belongs_to).I've got an Address
model, and there are several other models that I want to have one address. However, I'm confused by the wording of the docs. I've seen the morphMany
method, but my question is: should I use morphMany
even though I only want it to have one address, or is there something like a morphOne
method I should be using?
编辑:我的地址
模型有这些字段,只是为了帮助可视化:
My Address
model has these fields, just to help visualize:
Schema::create('addresses', function ($table)
{
$table->increments('id');
$table->string('street');
$table->string('street_more')->nullable();
$table->string('city');
$table->string('state')->nullable();
$table->string('country');
$table->string('postal_code');
$table->integer('addressable_id');
$table->string('addressable_type');
});
推荐答案
是的,有一个 morphOne 方法,我认为这是你应该使用的这种情况:。
还可以使用
$table->morphs('addressable');
而不是
$table->integer('addressable_id');
$table->string('addressable_type');
我在L4的自定义包中使用了morphOne,效果很好。
I've used morphOne in a custom package for L4 and works pretty well.
这篇关于Laravel雄辩的多态一对一?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!