我有3张桌子:
在我的作者模型中,我添加了:
public function courses () {
return $this->belongsToMany('App\Course', 'courses2authors')->where('status','=', 1);
}
“courses2authors”是数据透视表。然后在我的控制器中,我检索课程信息:
$authors = Author::where('status', '=', 1)->orderBy('pos')->with('courses')->get();
没关系,但我只在 - >课程中有category_id,如何在模型关系中添加类别名称。
我试着像:
return $this->belongsToMany('App\Course', 'courses2authors')
->where('status','=', 1)->join('categories', 'categories.id', '=',
'courses.category_id')->select('categories.name as categoria');
但是这样只采用类别名称而不是课程数据。
您可以在课程模型中使用类别定义belongsTo
关系。
课程模型
public function categories () {
return $this->belongsTo('App\Categories', 'category_id');
}
在用Author
检索Courses
时,你可以像这样使用。 (控制器代码)
$authors = Author::where('status', '=', 1)->orderBy('pos')
->with('courses',function($query){
$query->with('categories);
})->get();
如果你不想这样使用那么你可以在Courses
模型中设置$ with属性。
protected $with = ['categories']; // default with define here.
在控制器中使用: -
$authors = Author::where('status', '=', 1)->orderBy('pos')
->with('courses')->get();