简体   繁体   English

当涉及联合表时,我如何处理 Laravel Eloquent 关系?

[英]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.对于上下文 - 我有 2 个模型/表和它们之间的 1 个联合表。 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.如您所见,CategoryCourse 是联合表。 In the Category table - I have predefined categories like "Business" or "Web Development" and each Course can have multiple categories.在类别表中 - 我有预定义的类别,如“业务”或“Web 开发”,每个课程可以有多个类别。

So for example - a "Laravel" Course has the "Backend" and "Web Development" categories.例如,“Laravel”课程有“后端”和“Web 开发”类别。 And this relation is stored in the CategoryCourse table with category_id & course_id.并且此关系存储在具有 category_id 和 course_id 的 CategoryCourse 表中。

Now my question is - how do I form eloquent relationships between the 3 models?现在我的问题是 - 我如何在这 3 个模型之间形成雄辩的关系? If I only had 2 models ie Category & Course - it's a little more obvious.如果我只有 2 个模型,即类别和课程 - 它会更明显一些。 But now - I'm confused because I have 3 models.但是现在 - 我很困惑,因为我有 3 个模型。 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: 3个表的架构是:

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.请插话并指导我 - 我对 Laravel 中的关系有点陌生,我真的很想正确地使用它们。

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.两个模型( CourseCategory )都可以有一个与另一个模型关联的belongsToMany关系,这告诉 laravel 有一个连接它们两者的枢轴(连接表)。 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 .然后,您可以查询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您可以在https://laravel.com/docs/9.x/eloquent-relationships#many-to-many中了解有关Many to Many关系的更多信息

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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