Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel Eloquent polymorphic one-to-one?

Tags:

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?

EDIT: 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');
});
like image 397
BenjaminRH Avatar asked Feb 25 '14 11:02

BenjaminRH


People also ask

Does laravel 8 have one relation?

hasOne relationship in laravel is used to create the relation between two tables. hasOne means create the relation one to one. For example if a article has comments and we wanted to get one comment with the article details then we can use hasOne relationship or a user can have a profile table.

What is MorphTo in laravel?

"MorphTo" is used to define the relationship from a one-to-one or one-to-many polymorphic table to whichever model or models it is linked to. https://laravel.com/docs/5.7/eloquent-relationships#one-to-many-polymorphic-relations.

What is the use of whereHas in laravel?

whereHas() works basically the same as has() but allows you to specify additional filters for the related model to check.


2 Answers

Yes, there is a morphOne method 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 .

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.

like image 193
marcanuy Avatar answered Sep 28 '22 20:09

marcanuy


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

  public function address()
  {
      return $this->hasOne('App\Address', 'addressable_id','id')
                   ->where('addressable_type', 'App\Model');
  }
like image 27
Andrew Avatar answered Sep 28 '22 21:09

Andrew