我有下一个结构:
模型通话内容
public function credits(){
return $this->belongsToMany('App\models\Credit');
}
模型呼叫信用
public function content()
{
return $this->belongsToMany('App\models\Content');
}
我想要做的是提取一个内容的所有信用,但只选择我想要的列,使用以下代码:
$credits2=$this->content::with(array('credits'=>function($query){
$query->select('id','department','job');
}))->where('id',$id_content)->get();
我遇到的问题是,当我执行所有代码时,结果是:
[]
但如果我在mysql中进行正常查询,我可以弄清楚,对于电影存在信用。
我从其他论坛和stackoverflow帖子中提取了这段代码。
还有另一种简单的方法来指定列而不使用闭包:
$credits2 = $this->content::with('credits:credits.id,department,job')
->find($id_content->id);
问题是$ id_content是前一个查询的结果,所以如果我把$ id_content不起作用,为此我必须访问该列。
解决方案是:
$credits2=$this->content::with(array('credits'=>function($query){
$query->select('id','department','job');
}))->where('id',$id_content)->get();