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');
});
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.
"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.
whereHas() works basically the same as has() but allows you to specify additional filters for the related model to check.
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.
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');
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With