[英]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
. 我有一个多态模型“
Discussion
和其他可discussable
模型。
I have configured my morph map to translate project
to App\\Models\\Company\\Project
which is discussable
. 我已经配置了变形贴图,以将
project
转换为App\\Models\\Company\\Project
,这是可以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. 不幸的是
->where('discussable_type', $type)
不适用于变形贴图。
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);
}
A better approach could be defining relationships in the models: https://laravel.com/docs/5.8/eloquent-relationships#polymorphic-relationships 更好的方法可能是在模型中定义关系: https : //laravel.com/docs/5.8/eloquent-relationships#polymorphic-relationships
For example I got Project and Issue, two models that could be discussable. 例如,我得到了Project和Issue这两个可以讨论的模型。
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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.