atxpunkrock
atxpunkrock

Reputation: 514

Laravel Polymorphic Relation using full model name

I have a polymorphic relationship set up in Laravel 5.4. The relationship is working but the query is using the fully qualified model name.

select * from `contact_info` 
where `contact_info`.`entity_id` = '25'
and `contact_info`.`entity_id` is not null 
and `contact_info`.`entity_type` = 'App\Modules\User\Model\User' 
limit 1

The relationship is set on the User model:

/**
 * @description Method handles polymorphic contact relationship.
 * @return \Illuminate\Database\Eloquent\Relations\MorphOne
 */
public function contact()
{
    return $this->morphOne('App\Modules\Common\ContactInfo', 'entity');
}

and the ContactInfo model:

/**
 * @description Method establishes polymorphic relationship (tenant/user).
 * @return \Illuminate\Database\Eloquent\Relations\MorphTo
 */
public function entity()
{
    return $this->morphTo();
}

The actual table has the values set to 'user', 'tenant' and 'referrer' instead of the model names/namespaces. I found a little bit of information about relationship maps but don't know if that'll solve my issue here.

Basically I need to find out how to tell the code that 'App\Modules\User\Model\User' should be 'user' in the database.

Upvotes: 1

Views: 1075

Answers (1)

atxpunkrock
atxpunkrock

Reputation: 514

MorphMaps were the way to go. I added this to my AppServiceProvider boot method and it started pulling the data as expected:

use App\Modules\User;
use App\Modules\Tenant
Relation::morphMap([
    'user' => User::class,
    'tenant' => Tenant::class
]);

Query is now:

select * from `contact_info`
where `contact_info`.`entity_id` = '25'
and `contact_info`.`entity_id` is not null
and `contact_info`.`entity_type` = 'user' limit 1

This article helped me out tremendously.

Upvotes: 1

Related Questions