简体   繁体   中英

How do I approach Laravel Eloquent Relationships when there is a joint table involved?

For context - I have 2 models/tables and 1 joint table between them. They are:

  1. Category (Model/Table/Controller)
  2. Course (Model/Table/Controller)
  3. CategoryCourse (Model/Table)

As you can see, CategoryCourse is the joint table. In the Category table - I have predefined categories like "Business" or "Web Development" and each Course can have multiple categories.

So for example - a "Laravel" Course has the "Backend" and "Web Development" categories. And this relation is stored in the CategoryCourse table with category_id & course_id.

Now my question is - how do I form eloquent relationships between the 3 models? If I only had 2 models ie Category & Course - it's a little more obvious. But now - I'm confused because I have 3 models. So what relationship goes into which model? Because I want to be able to print all categories of a course in a table cell. How do I achieve this?

Schema for the 3 tables is:

courses: {
  id, name, difficulty, price
}

category: {
  id, name
}

categorycourse {
  id, course_id, category_id
}

Kindly chime in and guide me - I'm a little new to Relationships in Laravel and I really want to use to them correctly.

Both models ( Course & Category ) can have a belongsToMany relation associated with the other model, which tells laravel that there is a pivot (join table) that connects the two of them. There is no need for the third Model, since the framework deals with the pivot table behind the scenes.

class Course extends Model
{
    public function categories(): BelongsToMany
    {
        return $this->belongsToMany(Category::class);
    }
}

class Category extends Model
{
    public function courses(): BelongsToMany
    {
        return $this->belongsToMany(Course::class);
    }
}

You can then query Course::with('categories')->first()->categories & Category::with('courses')->first()->courses .

You can learn more about Many to Many relationships in https://laravel.com/docs/9.x/eloquent-relationships#many-to-many

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM