[英]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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.