Search code examples
phplaraveleloquentrelationshippolymorphic-associations

How to query a polymorphic Eloquent model providing the type and the id?


I have a polymorphic model Discussion and other models that are discussable.

I have configured my morph map to translate project to App\Models\Company\Project which is discussable.

I would like to write:

function get_all_discussions($type, $id) 
{
    return Discussion::orderBy('created_at', 'desc')
        ->where('discussable_type', $type)
        ->where('discussable_id', $id)
        ->get();
}

get_all_discussion('project', 1232);

Unfortunately ->where('discussable_type', $type) does not work with the morph map.

My current solution is to use this kludge:

function getMorphType($typeOrClass)
{
    $morphMap = array_flip(\Illuminate\Database\Eloquent\Relations\Relation::morphMap());

    return array_get($morphMap, $typeOrClass, $typeOrClass);
}

Solution

  • A better approach could be defining relationships in the models: https://laravel.com/docs/5.8/eloquent-relationships#polymorphic-relationships

    For example I got Project and Issue, two models that could be discussable.

    class Project
    {
        public function discussions()
        {
            return $this->morphMany(Discussion::class, 'discussable');
        }
    }
    
    class Issue
    {
        public function discussions()
        {
            return $this->morphMany(Discussion::class, 'discussable');
        }
    }
    

    Then if you want to get all discussion for a project or an issue:

    $project = Project::findOrFail(101);
    $issue = Issue::findOrFail(102);
    
    $project->discussions;
    $issue->discussions;