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?

编辑:我的Address型号有这些字段,只是为了帮助可视化:

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');

instead of

$table->integer('addressable_id');
$table->string('addressable_type');

我已经在L4的自定义包中使用过MorphOne,并且工作得很好.

Laravel相关问答推荐

URL类图中的循环关系

无法在终端cPanel中打开输入文件:artisan

如何在控制器中获取所需参数?

为什么使用 created_at 表在迁移错误中创建表?

LARVAL SAVE 中的关系有

如何在数据来自Rest API的flutter中创建下拉类别名称列表?

在 laravel 项目中放置 css 文件的位置

Laravel Blade 模板 @foreach 订单

如何使用 Eloquent Laravel 更新集合

Laravel 5.5 在迁移文件中设置整数字段的大小

如何仅从 laravel FormRequest 中获取经过验证的数据?

Laravel上传文件无法写入目录

Homebrew PHP 似乎没有链接

在 Laravel 中显示已注册的路由

日期验证 - 如何本地化/翻译字符串今天和明天

找不到框laravel/homestead

Laravel 事件、监听器、作业(job)、队列之间的区别

Laravel 5 Auth注销不起作用

连接到 tcp://smtp.mail.yahoo.com:465 超时

你如何在 Laravel 5.3 的新通知服务生成的Electron邮件中添加图像?