【问题标题】:How to query a polymorphic Eloquent model providing the type and the id?如何查询提供类型和 id 的多态 Eloquent 模型?
【发布时间】:2019-10-20 01:44:01
【问题描述】:

我有一个多态模型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);
}

【问题讨论】:

  • 您是在已有Discussion 实例之前还是之后添加了morphMap?检查您的数据库并查看是否填写了完整的类名或仅填写了'project'。如果填写了完整的类名,则可能通过将完整的类名替换为简写名称来修复。
  • @Teun morphMap 在我的AppServiceProvider@boot 中创建
  • “不适用于变形贴图”是什么意思? discussable_type 列已经包含“projects”而不是“App\Models\Company\Project”,对吧?

标签: php laravel eloquent relationship polymorphic-associations


【解决方案1】:

更好的方法是在模型中定义关系: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;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-08-05
    • 1970-01-01
    • 2017-10-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-15
    • 1970-01-01
    相关资源
    最近更新 更多