我正在尝试设置多态一对一的关系(has_one和poshs_to的多态等效物).i's get了一个世代odicetagcode模型,还有几个我想要有一个地址的其他模型。但是,我被文档的措辞混淆了。我已经看到了Address方法,但我的问题是:我应该使用morphMany,即使我只希望它有一个地址,还是有类似的东西我应该使用?

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

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/illumint/database/eloquent/model.php#l811

还可以使用

$table->morphs('addressable');
.

而不是

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

我已经在自定义包装中使用了L4的自定义包装,并效果很好。

其他提示

试试这个,我认为这比不支持的晶手机更好。

  public function address()
  {
      return $this->hasOne('App\Address', 'addressable_id','id')
                   ->where('addressable_type', 'App\Model');
  }
.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top