Laravel雄辩的多态一对一? [英] Laravel Eloquent polymorphic one-to-one?

查看:572
本文介绍了Laravel雄辩的多态一对一?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试设置一个多态的一对一关系(多态等效的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 方法,我认为这是你应该使用的这种情况: https://github.com/laravel/framework/blob/5.2/src/Illuminate/Database/Eloquent/Model.php#L811

还可以使用

$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雄辩的多态一对一?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆