//index.ctp, this forms points to action updateData in profilesController
$this->Form->input('User.lastname');
$this->Form->input('Profile.age');
$this->Form->input('Profile.height');
$this->Form->input('Associate.city');
$this->Form->end('Submit');
//user.php
Class User extends AppModel {
var $hasOne = array('Profile', 'Associate'};
var $primaryKey = 'user_id';
}
//profile.php
Class Profile extends AppModel {
var $belongsTo = array('User');
var $hasOne = 'Associate';
var $primaryKey = 'user_id';
}
//associate.php
Class Associate extends AppModel {
var $belongsTo = array('User');
var $primaryKey = 'user_id';
}
//profiles_controller.php
Class ProfilesController extends AppController{
function updateData(){
//output incoming request for debugging purposes
debug($this->request->data);
//here i fetch the db to get the id of user
$options =
array('conditions' => array('User.username' => $this->Auth->user('username')),
'fields' => array('User.id')
);
//find user id so we can find user in related tables
$id = $this->Profile->User->find('first', $options);
//here I modify request data so cakephp finds the users through primaryKeys
$this->request->data['Profile']['user_id'] = $id['User']['id'];
$this->request->data['Associate']['user_id'] = $id['User']['id'];
$this->request->data['User']['id'] = $id['User']['id'];
if($this->request->is('post'){
//this updates data in table no problem
$this->Profile->save($this->request->data);
//this updates data in table no problem either
$this->Profile->Associate->save($this->request->data);
//this returns false...it breaks here
$this->Profile->User->save($this->request->data);
}
}
}
структуры таблицы:CakePHP модели Ассоциация Не пинать в
User
|id|int|auto increment
|firstname|varchar
|lastname|varchar
|date|timestamp
Profile
|id|int|autoincrement
|user_id|int
|age|int
|height|int
Associate
|id|int|autoincrement
|user_id|int
|city|varchar
|country|varchar
Хорошо я знаю, что некоторые из вас могли бы сказать мне, почему я делаю это на profilesController и не на UsersController. Ну, моя идея состоит в том, чтобы отделить некоторые фактические важные данные пользователя от данных профиля, поэтому я намерен написать код профиля на ProfilesController ... по мере того, как я развивался, я предполагал, что одна и та же ассоциация модели автоматически обновит User.lastname поле в пользовательском table..but, что это та часть, где мой код брейки и я пытался, но я не могу заставить его работать
в настоящее время объединение в моем уме, по крайней мере, выглядит следующим образом:
У пользователя есть профиль Профиль пользователя У пользователя есть один ассоциированный пользователь Профиль принадлежит пользователю Associate принадлежит к профилю и пользователю
Может ли кто-нибудь сказать мне, что я делаю неправильно? Я следую тому, что, по моему мнению, является логическим подходом для моего приложения, cakephp обновляет модели Profile и Associate, но пользователь остается незатронутым.
Ваши отношения модели немного разряжены, и для одного вы используете 'user_id' в качестве первичного ключа для всех моделей? Это технически хорошо, но мне кажется, что вы не понимаете его цели. Не могли бы вы дать некоторый контекст для данных в профиле, пользователе и ассоциированном (опубликуйте их соответствующую структуру таблицы, то есть внешние ключи.) – Dunhamzzz