如何查询提供类型和 ID 的多态 Eloquent 模型?

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

我有一个多态模型 Discussion 和其他模型 discussable

我已经配置我的变形贴图以将 project 转换为 App\Models\Company\Project,即 discussable

我想写:

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);

遗憾的是 ->where('discussable_type', $type) 不适用于变形贴图。

我目前的解决方案是使用这个组合:

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

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

更好的方法是在模型中定义关系:https://laravel.com/docs/5.8/eloquent-relationships#polymorphic-relationships

比如我拿到了Project和Issue,两个可以讨论的模型。

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

那么如果你想获得对项目或问题的所有讨论:

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

$project->discussions;
$issue->discussions;