【问题标题】:Many to Many relationship with "Link table" Laravel 9与“链接表”Laravel 9 的多对多关系
【发布时间】:2023-01-13 22:58:23
【问题描述】:

我有一个模式“ProjectCase”,我正在尝试将模型“服务”链接到它。

我的数据库结构是这样的:

  • 工程案例
    • 编号
    • 标题
  • projectcases_to_services
    • projectcase_id
    • 服务编号
  • 服务
    • 编号
    • 标题

现在我试图在两者之间建立联系,并能够通过“ProjectCase”模型获得所有服务

我发现我应该创建一个函数,它使用多次通过功能。

我试过以下方法:

public function services() {
        return $this->hasManyThrough(Services::class, cases_to_services::class, 'case_id', 'id', 'id', 'service_id');
    }

但这会返回所有服务。

我错过了什么?

【问题讨论】:

  • 你自己很难不保持 Laravel 提供的开箱即用的命名约定。首先,尽量保持类名的单数形式。如果ProjectCases也可以叫Project,那就叫ProjectServices应该叫Service,中间表应该叫projectcase_service单数形式。指向模型的每个其他表链接都应该是复数形式,例如 servicesprojectcases。其次,中间表应该按时间顺序排列,service_projectcases 是错误的;)

标签: laravel has-many-through


【解决方案1】:

使用Many To Many Relationships

所以在ProjectCases模型中添加如下关系

 public function services() {
        return $this->belongsToMany(Services::class, 'projectcases_to_services', 'projectcase_id', 'service_id');
    }

如果您看到 belongsToMany 方法的参数选项

/**
     * Define a many-to-many relationship.
     *
     * @param  string  $related
     * @param  string|null  $table
     * @param  string|null  $foreignPivotKey
     * @param  string|null  $relatedPivotKey
     * @param  string|null  $parentKey
     * @param  string|null  $relatedKey
     * @param  string|null  $relation
     * @return IlluminateDatabaseEloquentRelationsBelongsToMany
     */
    public function belongsToMany($related, $table = null, $foreignPivotKey = null, $relatedPivotKey = null,
                                  $parentKey = null, $relatedKey = null, $relation = null)
    {
    }

建议你遵循模型和数据库表的 laravel 命名约定。这样你就可以保持代码干净

laravel 的一些命名约定最佳实践

图片内容使用自Naming Convention Laravel

【讨论】:

    【解决方案2】:

    对于多对多关系,您需要在 ProjectCases 模型上定义一个“belongsToMany”关系:

    public function services()
    {
        return $this->belongsToMany(Services::class, 'projectcases_to_services', 'projectcase_id', 'service_id');
    }
    

    您可能还想看看此处给出的解释: https://laravel.com/docs/9.x/eloquent-relationships#many-to-many

    【讨论】:

    • 中间表 projectcases_to_services 应该重命名为 projectcase_service 以便开箱即用。
    • @dbf 是的,如果您要遵循 laravel 命名约定,您已经对如何命名模型和表进行了非常全面的描述 :) 如果您这样做,将 services() 实现为 return $this->belongsToMany(Service::class) 就足够了
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-10-16
    • 2017-06-21
    • 2018-03-16
    • 2014-04-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多