如何用3 PrimaryKey编写文件yml多对多表



如果我们的情况是标准视图,您有两个表和一个三进制,并且可以通过以下文档轻松管理

但是如果我们有三个而不是两个表,那么三元制由3个PrimaryKey组成,当我写我的yml文件时?

示例:

假设我有一个用户参加了一个课程。所以我有一个users表,courses表和users_has_courses (useri_id, course_id)。这是标准的多对多情况。但我也有一个表invoices,因此一个表users_courses_invoices,其中有三个primaykey (user_id, course_id, invoice_id)。

在您的情况下,您有UserCourse模型,它们与以(user_id, course_id)对为键的多对多关系相关联。我会将此模型称为订阅,并赋予其自己的标识符,然后我将此模型与Invoice模型链接起来,因此您的最终方案(最小版本)可以是:

User:
  columns:
    id:
      type: integer
      primary: true
Course:
  columns:
    id:
      type: integer
      primary: true
Subscription:
  columns:
    id:
      type: integer
      primary: true
    user_id:
      type: integer
      notnull: true
    course_id:
      type: integer
      notnull: true
  relations:
    User:
      foreignAlias: Subscriptions
    Course:
      foreignAlias: Subscriptions
Invoice:
  columns:
    id:
      type: integer
      primary: true
    subscription_id:
      type: integer
      notnull: true
  relations:
    Subscription:
      foreignAlias: Subscription
      foreignType: One

这样你就有了一个规范化的数据库,你可以访问来自用户和课程的发票,代码如下:

$user->Subscriptions->getFirst()->Invoice
$course->Subscriptions->getFirst()->Invoice

如果你想要给定用户的所有发票,你可以用这种方式进行查询

InvoiceTable::getInstance()->createQuery('i')
    ->select('i.*')
    ->leftJoin('i.Subscription s')->leftJoin('s.User u')
    ->where('u.id = ?', $user_id);

如果您想要给定课程的所有发票,同样适用。

最新更新