如何在多态关系中按类型选择列?



正如标题所说,我有一个多对多的多态关系,我想选择每个模型的某些列。我已经查看了Laravel的文档,但我只找到了这段代码,它与我正在寻找的代码相似。

$comments = AppComment::whereHasMorph(
'commentable', 
['AppPost', 'AppVideo'], 
function (Builder $query, $type) {
if ($type === 'AppPost') {
$query->where('content', 'like', 'foo%');
}
}
)->get();

我想做类似的事情,但这样:

$comments = AppComment::with(
'commentable', 
['AppPost', 'AppVideo'], 
function (Builder $query, $type) {
if ($type === 'AppPost') {
$query->select('id', 'title');
}elseif($type === 'AppVideo'){
$query->select('id', 'name');
}
}
)->get();

我希望你能理解我并帮助解决这个问题,谢谢

假设每个模型类中的多态方法如下所示:

public function commentType() 
{ 
return $this->morphOne('AppComment', 'commentable');
}

一个简单的方法是向 Comment 类添加两个方法:

公共函数 getIsPostAttribute(( { 返回 $this->评论类型 == '应用\发布'; }

公共函数 getIsVideoAttribute(( { 返回 $this->注释类型 == '应用\视频'; }

然后,只需:

$comment = AppComment::find(1)->isPost; // True or False
$comment = AppComment::find(1)->isVideo; // True or False

现在查询将很容易做到:

$posts  = AppComment::where('isPost', true)->get();
$videos = AppComment::where('isVideo', true)->get();

最新更新