【问题标题】:cake php 3.x, model join 3 tablecake php 3.x,模型加入 3 表
【发布时间】:2023-03-11 19:49:01
【问题描述】:

我试图在 cake php 中加入 3 个表。 我会缩短表格,我必须让它变得简单。

table_users(
    id int primary key,
    username varchar(10),
    password varchar(10),
)


table_details(
   id int primary key,
   user_id int, //fk of table_users.id
   //more fields here
)

table_ot(
       id int primary key,
       user_id int, //fk of table_users.id
       //more fields here
    )

我计划使用 user_id 加入 table_details 和 table_ot。 在cake bake生成的模型中,table_details是join table_users,table_ot是table_users。

但是 table_details 没有加入 table_ot。 这是table_details和table_ot的内容。

   $this->belongsTo('table_users', [
        'foreignKey' => 'user_id',
        'joinType' => 'INNER'
    ]);

也试过这个在控制器里还是不行。

   $Overtime = $this->table_ot->find()->all(array('joins' => 
        array(
            'table' => 'table_table_details',
            'alias' => 'table_table_details',
            'type' => 'full',
            'foreignKey' => false,
            'conditions'=> array('table_ot.user_id = table_table_details.user_id')
        )
    )); 

任何建议..请帮助

【问题讨论】:

  • 看起来 table_details 和 table_ot 没有关系..那么你为什么需要加入他们?在 cakephp 中使用 contains 比 join 更容易。
  • @ManoharKhadka 我需要从 table_ot 中提取 table_details 中的一些字段。它们具有相同的 user_id 值。在 sql 语句中,它们可以像 table_details.user_id = table_ot.user_id 一样连接

标签: php mysql cakephp join


【解决方案1】:

正如您在问题中指出的那样,您已经设置了表格关联。所以你可以这样写你的查询:

$this->table_ot->find("all",[
    "contain" => [
        "table_users" => ["table_details"]
    ]
]);

使用例如 toArray() 执行此查询后,您可以访问与 table_ot 关联的 table_details 记录,如下所示:

$detailId = $results[0]->table_users->table_details->id;

作为替代方案,我建议您尝试像这样连接这两个表:

//in initialize() method of your ot_table:
$this->hasOne("table_details")
    ->setForeignKey("user_id")
    ->setBindingKey("user_id");

此处列出了每种关联类型的所有可用选项:https://book.cakephp.org/3.0/en/orm/associations.html

【讨论】:

    【解决方案2】:
    You have to add another field in table_ot to join with table_details according to cake convention. Because you have a foreign just to join with user table.
    
    table_ot(
           id int primary key,
           user_id int, //fk of table_users.id
           details_id int, //fk of table_details.id
           //more fields here
        )
    Then add this code in table of table_ot
    $this->belongsTo('table_details', [
            'foreignKey' => 'details_id',
            'joinType' => 'INNER'
        ]);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-10-14
      • 2023-03-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-16
      • 2017-08-14
      • 1970-01-01
      相关资源
      最近更新 更多