cake php 3.x,model join 3 table

时间:2017-05-26 03:56:33

标签: php mysql cakephp join

我试图在蛋糕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连接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')
        )
    )); 

任何建议..请帮助

2 个答案:

答案 0 :(得分:0)

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

http://97.987.98.987

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

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

作为替代方案,我建议你尝试加入这两个表:

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

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

答案 1 :(得分:0)

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'
    ]);