关系BelongsToMany与其他数据

问题描述 投票:0回答:1

我有3张桌子:

  1. 课程(有category_id)
  2. 作者
  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');

但是这样只采用类别名称而不是课程数据。

laravel laravel-5 relationship laravel-5.5 laravel-eloquent
1个回答
4
投票

您可以在课程模型中使用类别定义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();
© www.soinside.com 2019 - 2024. All rights reserved.