关系BelongToMany与其他数据

时间:2018-03-03 10:16:22

标签: laravel laravel-5 relationship laravel-5.5 laravel-eloquent

我有3张桌子:

  1. 课程(有category_id)
  2. 作者
  3. 课程类别
  4. 在我的作者模型中,我添加了:

        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');
    

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

0 个答案:

没有答案