簡體   English   中英

當涉及聯合表時,我如何處理 Laravel Eloquent 關系?

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

對於上下文 - 我有 2 個模型/表和它們之間的 1 個聯合表。 他們是:

  1. 類別(模型/表/控制器)
  2. 課程(模型/表格/控制器)
  3. 類別課程(模型/表格)

如您所見,CategoryCourse 是聯合表。 在類別表中 - 我有預定義的類別,如“業務”或“Web 開發”,每個課程可以有多個類別。

例如,“Laravel”課程有“后端”和“Web 開發”類別。 並且此關系存儲在具有 category_id 和 course_id 的 CategoryCourse 表中。

現在我的問題是 - 我如何在這 3 個模型之間形成雄辯的關系? 如果我只有 2 個模型,即類別和課程 - 它會更明顯一些。 但是現在 - 我很困惑,因為我有 3 個模型。 那么什么關系進入哪個模型呢? 因為我希望能夠在表格單元格中打印課程的所有類別。 我如何實現這一目標?

3個表的架構是:

courses: {
  id, name, difficulty, price
}

category: {
  id, name
}

categorycourse {
  id, course_id, category_id
}

請插話並指導我 - 我對 Laravel 中的關系有點陌生,我真的很想正確地使用它們。

兩個模型( CourseCategory )都可以有一個與另一個模型關聯的belongsToMany關系,這告訴 laravel 有一個連接它們兩者的樞軸(連接表)。 不需要第三個模型,因為框架在幕后處理數據透視表。

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

然后,您可以查詢Course::with('categories')->first()->categories & Category::with('courses')->first()->courses

您可以在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