草庐IT

php - 无法在数据透视表中创建多个多对多关系

coder 2023-10-19 原文

我正在尝试在 Laravel 5 中创建一个应用程序来跟踪患者的医学检查,以便我可以创建患者病史,我使用 Eloquent 作为我的模型抽象推荐。

为此,我使用 laravel 迁移创建了三个表和一个数据透视表,如下图所示:

用户可以是医生或管理员,他们输入患者针对他们所做的特定检查的分数结果,例如我有一个数据透视表,其中包含三个外键以关联三个实体:

  • 考试编号
  • 患者编号
  • 用户编号

在 Eloquent 中,我根据 Laravel 文档制作了这些多对多模型 Many To Many支持提议的业务逻辑:

<?php
    // Patient.php
    class Patient extends Model
    {
        public function exams() {

            return $this->belongsToMany('App\Exam', 'exam_patient');
        }
    }

    // Exam.php
    class Exam extends Model
    {
        public function patients()
        {

            return $this->belongsToMany('App\Patient', 'exam_patient');
        }

        public function users()
        {

            return $this->belongstoMany('App\User', 'exam_patient');
        }
    }

    // User.php
    class User extends Model
    {
        public function exams() {

            return $this->belongsToMany('App\Exam', 'exam_patient');
        }
    }

在修补程序中,我尝试在进行重大更改之前模拟一个常见用例:医生对患者进行检查:

 >>> $user= App\User::first()
=> App\User {#671
     id: "1",
     name: "Victor",
     email: "",
     created_at: "2015-10-10 18:33:54",
     updated_at: "2015-10-10 18:33:54",
   }

>>> $patient= App\Patient::first()
=> App\Patient {#669
     id: "1",
     username: "",
     name: "Tony",
     lastname: "",
     birthday: "0000-00-00",
     created_at: "2015-10-10 18:32:56",
     updated_at: "2015-10-10 18:32:56",
   }

>>> $exam= App\Exam::first()
=> App\Exam {#680
     id: "1",
     name: "das28",
     title: "Das28",
     created_at: "2015-10-10 18:31:31",
     updated_at: "2015-10-10 18:31:31",
   }

>>> $user->save()
=> true
>>> $patient->save()
=> true
>>> $exam->save()
=> true

问题是当我尝试链接(或附加)至少两个模型时出现以下错误:

   >>> $patient->exams()->attach(1) 
Illuminate\Database\QueryException with message
    'SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a
    child row: a foreign key constraint fails (`cliniapp`.`exam_patient`, CONSTRAINT
    `exam_patient_user_id_foreign` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`)
    ON DELETE CASCADE) (SQL: insert into `exam_patient` (`exam_id`, `patient_id`)
    values (1, 1))'

如果我连其中两个都不能连接,我怎么能连接这三个模型呢?修补程序中有什么方法可以大量附加它们,以便我可以将它们关联到我的数据透视表 (exam_patient) 中,而 MySql 不会显示该错误,或​​者如果我的方法有误?非常感谢任何帮助。

最佳答案

当您的 Many to Many 上有额外字段时关系,您必须在声明关系时“注册”它们,如上述链接的检索中间表列部分所示。

因此,您应该始终声明您的“额外”数据透视表,这些表因您定义关系的位置而异:

class Patient extends Model
{
    public function exams()
    {
        return $this->belongsToMany('App\Exam', 'exam_patient')->withPivot('user_id');
    }
}

class Exam extends Model
{
    public function patients()
    {
        return $this->belongsToMany('App\Patient', 'exam_patient')->withPivot('user_id');
    }

    public function users()
    {
        return $this->belongstoMany('App\User', 'exam_patient')->withPivot('patient_id');
    }
}

class User extends Model
{
    public function exams()
    {
        return $this->belongsToMany('App\Exam', 'exam_patient')->withPivot('patient_id');
    }
}

Attaching/Detaching 部分,您可以看到您可以像这样设置这些额外的字段:

$patient->exams()->attach($exam->id, ['user_id' => $user->id]);

你的问题是,当你在没有为 user_id 列传递数据的情况下创建患者/检查关系时,你的 exam_patient 表上的 user_id 外键约束失败了,所以上面的方法会起作用。

如果您出于某种原因不想始终像那样传递 user_id,您还可以使该 user_id 列在数据库中可以为空。

当然,有人认为使用两个数据透视表(exam_patient 和 exam_user)或使用多对多多态关系会是一种更好的方法。


Laravel docs on polymorphic relations 可以看出,为了在此处实现它们,我们将删除 exam_patient 表以​​获得 examable 表,该表将包含 3 列:exam_id、examable_id 和 examable_type。

模型看起来像:

class Patient extends Model
{
    public function exams()
    {
        return $this->morphToMany('App\Exam', 'examable');
    }
}

class Exam extends Model
{
    public function patients()
    {
        return $this->morphedByMany('App\Patient', 'examable');
    }

    public function users()
    {
        return $this->morphedByMany('App\User', 'examable');
    }
}

class User extends Model
{
    public function exams()
    {
        return $this->morphToMany('App\Exam', 'examable');
    }
}

要完全更新 examable 表,您需要执行以下操作:

$exam->patients()->save($patient);
$exam->users()->save($user);

所以这是两个查询而不是一个,你失去了外键关系,“examables”是一个尴尬的名字。

的论点是,这种关系更具声明性,并且更容易处理属于多个用户/医生的单个患者的单个检查。

关于php - 无法在数据透视表中创建多个多对多关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33072716/

有关php - 无法在数据透视表中创建多个多对多关系的更多相关文章

  1. ruby-on-rails - 由于 "wkhtmltopdf",PDFKIT 显然无法正常工作 - 2

    我在从html页面生成PDF时遇到问题。我正在使用PDFkit。在安装它的过程中,我注意到我需要wkhtmltopdf。所以我也安装了它。我做了PDFkit的文档所说的一切......现在我在尝试加载PDF时遇到了这个错误。这里是错误:commandfailed:"/usr/local/bin/wkhtmltopdf""--margin-right""0.75in""--page-size""Letter""--margin-top""0.75in""--margin-bottom""0.75in""--encoding""UTF-8""--margin-left""0.75in""-

  2. ruby-on-rails - Rails 3 中的多个路由文件 - 2

    Rails2.3可以选择随时使用RouteSet#add_configuration_file添加更多路由。是否可以在Rails3项目中做同样的事情? 最佳答案 在config/application.rb中:config.paths.config.routes在Rails3.2(也可能是Rails3.1)中,使用:config.paths["config/routes"] 关于ruby-on-rails-Rails3中的多个路由文件,我们在StackOverflow上找到一个类似的问题

  3. ruby-on-rails - 在 Ruby 中循环遍历多个数组 - 2

    我有多个ActiveRecord子类Item的实例数组,我需要根据最早的事件循环打印。在这种情况下,我需要打印付款和维护日期,如下所示:ItemAmaintenancerequiredin5daysItemBpaymentrequiredin6daysItemApaymentrequiredin7daysItemBmaintenancerequiredin8days我目前有两个查询,用于查找maintenance和payment项目(非排他性查询),并输出如下内容:paymentrequiredin...maintenancerequiredin...有什么方法可以改善上述(丑陋的)代

  4. ruby - 解析 RDFa、微数据等的最佳方式是什么,使用统一的模式/词汇(例如 schema.org)存储和显示信息 - 2

    我主要使用Ruby来执行此操作,但到目前为止我的攻击计划如下:使用gemsrdf、rdf-rdfa和rdf-microdata或mida来解析给定任何URI的数据。我认为最好映射到像schema.org这样的统一模式,例如使用这个yaml文件,它试图描述数据词汇表和opengraph到schema.org之间的转换:#SchemaXtoschema.orgconversion#data-vocabularyDV:name:namestreet-address:streetAddressregion:addressRegionlocality:addressLocalityphoto:i

  5. ruby-on-rails - Rails - 一个 View 中的多个模型 - 2

    我需要从一个View访问多个模型。以前,我的links_controller仅用于提供以不同方式排序的链接资源。现在我想包括一个部分(我假设)显示按分数排序的顶级用户(@users=User.all.sort_by(&:score))我知道我可以将此代码插入每个链接操作并从View访问它,但这似乎不是“ruby方式”,我将需要在不久的将来访问更多模型。这可能会变得很脏,是否有针对这种情况的任何技术?注意事项:我认为我的应用程序正朝着单一格式和动态页面内容的方向发展,本质上是一个典型的网络应用程序。我知道before_filter但考虑到我希望应用程序进入的方向,这似乎很麻烦。最终从任何

  6. ruby-on-rails - 无法使用 Rails 3.2 创建插件? - 2

    我对最新版本的Rails有疑问。我创建了一个新应用程序(railsnewMyProject),但我没有脚本/生成,只有脚本/rails,当我输入ruby./script/railsgeneratepluginmy_plugin"Couldnotfindgeneratorplugin.".你知道如何生成插件模板吗?没有这个命令可以创建插件吗?PS:我正在使用Rails3.2.1和ruby​​1.8.7[universal-darwin11.0] 最佳答案 随着Rails3.2.0的发布,插件生成器已经被移除。查看变更日志here.现在

  7. ruby - 无法运行 Rails 2.x 应用程序 - 2

    我尝试运行2.x应用程序。我使用rvm并为此应用程序设置其他版本的ruby​​:$rvmuseree-1.8.7-head我尝试运行服务器,然后出现很多错误:$script/serverNOTE:Gem.source_indexisdeprecated,useSpecification.Itwillberemovedonorafter2011-11-01.Gem.source_indexcalledfrom/Users/serg/rails_projects_terminal/work_proj/spohelp/config/../vendor/rails/railties/lib/r

  8. ruby-on-rails - 无法在centos上安装therubyracer(V8和GCC出错) - 2

    我正在尝试在我的centos服务器上安装therubyracer,但遇到了麻烦。$geminstalltherubyracerBuildingnativeextensions.Thiscouldtakeawhile...ERROR:Errorinstallingtherubyracer:ERROR:Failedtobuildgemnativeextension./usr/local/rvm/rubies/ruby-1.9.3-p125/bin/rubyextconf.rbcheckingformain()in-lpthread...yescheckingforv8.h...no***e

  9. ruby - 无法让 RSpec 工作—— 'require' : cannot load such file - 2

    我花了三天的时间用头撞墙,试图弄清楚为什么简单的“rake”不能通过我的规范文件。如果您遇到这种情况:任何文件夹路径中都不要有空格!。严重地。事实上,从现在开始,您命名的任何内容都没有空格。这是我的控制台输出:(在/Users/*****/Desktop/LearningRuby/learn_ruby)$rake/Users/*******/Desktop/LearningRuby/learn_ruby/00_hello/hello_spec.rb:116:in`require':cannotloadsuchfile--hello(LoadError) 最佳

  10. ruby - 多个属性的 update_column 方法 - 2

    我有一个具有一些属性的模型:attr1、attr2和attr3。我需要在不执行回调和验证的情况下更新此属性。我找到了update_column方法,但我想同时更新三个属性。我需要这样的东西:update_columns({attr1:val1,attr2:val2,attr3:val3})代替update_column(attr1,val1)update_column(attr2,val2)update_column(attr3,val3) 最佳答案 您可以使用update_columns(attr1:val1,attr2:val2

随机推荐