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

Php 如何在多态关系中按类型选择列?,php,laravel,Php,Laravel,正如标题所说,我有一个多对多的多态关系,我想选择每个模型的某些列。我已经看过了Laravel的文档,但我只找到了这段代码,它与我正在寻找的代码类似 $comments=App\Comment::whereHasMorph( “可评论的”, ['App\Post','App\Video'], 函数(生成器$query,$type){ 如果($type=='App\Post'){ $query->where('content','like','foo%'); } } )->get(); 我想做一些

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

$comments=App\Comment::whereHasMorph(
“可评论的”,
['App\Post','App\Video'],
函数(生成器$query,$type){
如果($type=='App\Post'){
$query->where('content','like','foo%');
}
}
)->get();
我想做一些类似的事情,但这样做:

$comments=App\Comment::with(
“可评论的”,
['App\Post','App\Video'],
函数(生成器$query,$type){
如果($type=='App\Post'){
$query->select('id','title');
}elseif($type==='App\Video'){
$query->select('id','name');
}
}
)->get();

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

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

public function commentType() 
{ 
    return $this->morphOne('App\Comment', 'commentable');
}
一种简单的方法是向Comment类添加两个方法:

公共函数getIsPostAttribute() { 返回$this->commentType==“App\Post”; }

公共函数getIsVideoAttribute() { 返回$this->commentType=='App\Video'; }

然后,只是:

$comment = App\Comment::find(1)->isPost; // True or False
$comment = App\Comment::find(1)->isVideo; // True or False
现在查询将很容易:

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

这不是我要找的,我希望所有的注释都在一个查询中,每个模型都选择特定的列