Laravel 8.x,3种模型以及多对多关系 [英] Laravel 8.x, 3 models and many to many relationship

查看:35
本文介绍了Laravel 8.x,3种模型以及多对多关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是laravel的新手,请尝试以下操作:

I am new to laravel and trying the following:

我有这些表:

学科:id |名称

专长:id |名称

类别:id |名称

discipline_specialty(数据透视表):id |学科编号|specialties_id

discipline_specialty (pivot table): id | discipline_id | specialties_id

学科模型:

public function specialties()
    {
        return $this->belongsToMany(Specialty::class);
    }

专业模型:

public function disciplines()
    {
        return $this->belongsToMany(Discipline::class);
    }

我的问题是:

我如何将类别(与许多类别相关联)与数据透视表学科_特殊性,以便使用学科和专业ID来访问类别名称?我曾想过一个附加的数据透视表,该数据表将类别ID和学科专业ID链接在一起,但是我不知道这是否是最佳解决方案以及如何做到这一点.你有什么建议吗?感谢您的帮助.

how can I relate (many to many) the categories to the pivot table discipline_specialty in order to access the category name with the discipline and specialty ids? I had thought of an additional pivot table that linked category id and discipline_specialty id but I don't know if it's the best solution and how to do it. Do you have any suggestions? Any help is appreciated.

推荐答案

您可以引入结点/枢轴模型,该模型会将这3个关系关联为Discipline/中的多对一/belongsTo和一对多/hasMany/专业/类别.

You can introduce a junction/pivot model that will relate these 3 relations as many-to-one/belongsTo and one-to-many/hasMany from Discipline/Speciality/Category.

Discipline       Speciality     Category
    \\              ||             //
     \\             ||            //
      DisciplineSpecialityCategory

DisciplineSpecialityCategory 模型将具有以下属性或FK

This DisciplineSpecialityCategory model will have following attributes or FKs

表:学科特殊类别

  • discipline_id
  • speciality_id
  • category_id

现在,您的模型定义就像

Now you model definitions will be like

class Discipline extends Model
{
    public function disciplineSpecialityCategory()
    {
        return $this->hasMany(DisciplineSpecialityCategory::class, 'id', 'discipline_id');
    }
}

class Speciality extends Model
{
    public function disciplineSpecialityCategory()
    {
        return $this->hasMany(DisciplineSpecialityCategory::class, 'id', 'speciality_id');
    }
}

class Category extends Model
{
    public function disciplineSpecialityCategory()
    {
        return $this->hasMany(DisciplineSpecialityCategory::class, 'id', 'category_id');
    }
}

class DisciplineSpecialityCategory extends Model
{
    public function discipline()
    {
        return $this->belongsTo(Discipline::class, 'id', 'discipline_id');
    }
    public function speciality()
    {
        return $this->belongsTo(Speciality::class, 'id', 'speciality_id');
    }
    public function category()
    {
        return $this->belongsTo(Category::class, 'id', 'category_id');
    }
}

这篇关于Laravel 8.x,3种模型以及多对多关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆