[英]CakePHP how to add data from another field of a related model
这是我教程之外的第一个应用程序,因此我不知道如何很好地表达我的问题。
好吧,我有这两个表:
User ( id, code )
Hours ( id, user_id, created)
我想知道如何使用user_code
将条目添加到Hours
表中。
我尝试使用code
值获取User
表的数据,然后使用findBy
并传递给patchEntity
但它不起作用。
我没有很多要处理的信息,但我会尽力而为。
我想知道如何使用user_code将条目添加到Hours表中
您提到使用patchEntity,所以这是在更新已经存在的信息。 假设user_code是您在此处谈论的“代码”列,请首先通过其代码查找用户:
$users_tbl = TableRegistry::get('Users');
// find the user
$user = $users_tbl->findByCode($user_code)->first();
if ($user) {
// replace '$this->request->data() with whatever patch data you wanted
$users_tbl->patchEntity($user, $this->request->data(), [
'associated' => ['Hours']
]
if ($users_tbl->save($user)) {
// success!
} else {
// error!
}
} else {
// error!
}
它还将取决于您如何传递数据 (我的'$ this-> request-> data()所在的位置,或者数组可能是什么)-它需要匹配正确的列名并且正确格式在这里列出。
但是,这正在更新数据。 只需添加数据,您就可以加载小时表并添加一个新条目,其中包含从用户搜索中获取的user_id:
$hours_tbl = TableRegistry::get('Hours');
$hours = $hours_tbl->newEntity([
'user_id' => $user->id // $user populated from same method earlier
]);
/* assumed 'id' was autoincrementing and 'created' was populated
through Timestamp behavior */
if ($hours_tbl->save($hours)) {
// yay!
} else {
// boo
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.