Laravel Eloquent 多态一对一?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22012877/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 09:05:48  来源:igfitidea点击:

Laravel Eloquent polymorphic one-to-one?

laravellaravel-4eloquentpolymorphic-associations

提问by BenjaminRH

I'm trying to setup a polymorphic one-to-one relationship (the polymorphic equivalent of has_one and belongs_to).I've got an Addressmodel, 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 morphManymethod, but my question is: should I use morphManyeven though I only want it to have one address, or is there something like a morphOnemethod I should be using?

我正在尝试建立一个多态的一对一关系(has_one 和belongs_to 的多态等价物)。我有一个Address模型,还有其他几个模型我想要一个地址。但是,我对文档的措辞感到困惑。我已经看到了该morphMany方法,但我的问题是:morphMany即使我只希望它有一个地址,morphOne我应该使用它,还是应该使用类似的方法?

EDIT: My Addressmodel has these fields, just to help visualize:

编辑:我的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');
});

回答by marcanuy

Yes, there is a morphOnemethod and I think is the one you should use in this case: https://github.com/laravel/framework/blob/5.2/src/Illuminate/Database/Eloquent/Model.php#L811.

是的,有一种morphOne方法,我认为在这种情况下您应该使用该方法:https: //github.com/laravel/framework/blob/5.2/src/Illuminate/Database/Eloquent/Model.php#L811

Also you can use

你也可以使用

$table->morphs('addressable');

instead of

代替

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

I've used morphOne in a custom package for L4 and works pretty well.

我在 L4 的自定义包中使用了 morphOne,并且效果很好。

回答by Andrew

Try this one, I think this is better than morphOne that not supported.

试试这个,我认为这比不支持的 morphOne 更好。

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