首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >蛋糕php 3.x,模型连接3表

蛋糕php 3.x,模型连接3表
EN

Stack Overflow用户
提问于 2017-05-26 11:56:33
回答 2查看 183关注 0票数 0

我正在尝试加入蛋糕php中的3个表。我会把桌子缩短,我得把它简单化。

代码语言:javascript
复制
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
    )

我计划在table_details和table_ot中使用user_id。在蛋糕烘焙生成的模型中,table_details加入table_users,table_ot加入table_users。

但table_details不会加入table_ot。这是table_details和table_ot的内容。

代码语言:javascript
复制
   $this->belongsTo('table_users', [
        'foreignKey' => 'user_id',
        'joinType' => 'INNER'
    ]);

我在控制器里也试过这个,还是不能用。

代码语言:javascript
复制
   $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')
        )
    )); 

任何建议..请帮帮忙

EN

回答 2

Stack Overflow用户

发布于 2017-05-26 14:59:37

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

代码语言:javascript
复制
$this->table_ot->find("all",[
    "contain" => [
        "table_users" => ["table_details"]
    ]
]);

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

代码语言:javascript
复制
$detailId = $results[0]->table_users->table_details->id;

作为另一种选择,我建议您尝试连接这两个表,如下所示:

代码语言:javascript
复制
//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

票数 0
EN

Stack Overflow用户

发布于 2017-08-19 14:44:00

代码语言:javascript
复制
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'
    ]);
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/44193328

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档