我正在尝试加入蛋糕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
)我计划在table_details和table_ot中使用user_id。在蛋糕烘焙生成的模型中,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')
)
)); 任何建议..请帮帮忙
发布于 2017-05-26 14:59:37
正如您在问题中指出的,您已经设置了表关联。所以你可以像这样写你的查询:
$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
发布于 2017-08-19 14:44:00
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'
]);https://stackoverflow.com/questions/44193328
复制相似问题