繁体   English   中英

蛋糕php 3.x,模型联接3表

[英]cake php 3.x, model join 3 table

我试图加入蛋糕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。 在蛋糕烘焙生成的模型中,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')
        )
    )); 

任何建议..请帮助

正如您在问题中指出的那样,您已经建立了表关联。 因此,您可以这样编写查询:

$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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM