samedi 3 mars 2018

Relationship BelongToMany with additional data

I've 3 tables:

  1. Courses (have category_id)
  2. Authors
  3. Categories (of courses)

In my Authors model I've added:

    public function courses () {
        return $this->belongsToMany('App\Course', 'courses2authors')->where('status','=', 1);
}

"courses2authors" is the pivot table. Then in my controller I retrieve courses info with:

$authors = Author::where('status', '=', 1)->orderBy('pos')->with('courses')->get();

It's ok but I've only the category_id in ->courses, how to add category name in the model relationship.

I try something like:

return $this->belongsToMany('App\Course', 'courses2authors')
->where('status','=', 1)->join('categories', 'categories.id', '=',
'courses.category_id')->select('categories.name as categoria');

But in this way in take only the category name and not the course data.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire