Как сохранить до 2 HABTM и 1 принадлежит для связи с cakeStack Overflow

Я пытаюсь сохранить данные с одного из моих контроллеров с именем «EvidenceController.php». Проблема, с которой я столкнулся, заключается в том, что не все ассоциации с моей моделью замечаний сохранятся. Сохранит только связь Remark с Evidence, и она сохранит только Доказательство_идентификации и дату создания. Ни одна из других ассоциаций Remark не спасет. Вот мои настройки таблицы для проектов, доказательства, замечания, пользователи, evidences_remarks, users_remarks:

projects.id, projects.title, projects.description, projects.created, projects.approved, projects.approvedby, projects.user_id

evidences.id, evidences.title, evidences.date, evidences.description, evidences.sourcetype, evidences.source, evidences.pdfloc, evidences.author, evidences.authorcred, evidences.user_id, evidences.created

remarks.id, remarks.evidence_id, remarks.remark, remarks.created

users.id, users.username, users.password, users.full_name, users.type, users.created

evidences_remarks.id, evidences_remarks.evidence_id, evidences_remarks.remark_id

users_remarks.id, users_remarks.user_id, users_remarks.remark_id

Вот мои модели:

Project.php

App::uses('AppModel', 'Model');

class Project extends AppModel {

var $name = 'Project';
public $displayField = 'title';public $validate = array(
'id' => array(
'notEmpty' => array(
'rule' => array('notEmpty'),

),
'numeric' => array(
'rule' => array('numeric'),
),
),
'title' => array(
'notEmpty' => array(
'rule' => array('notEmpty'),
),
),
'created' => array(
'datetime' => array(
'rule' => array('datetime'),
),
),
'approved' => array(
'numeric' => array(
'rule' => array('numeric'),
),
),
'user_id' => array(
'numeric' => array(
'rule' => array('numeric'),
),
),
);

public $belongsTo = array(
'User' => array(
'className' => 'User',
'foreignKey' => 'user_id',
'conditions' => '',
'fields' => '',
'order' => ''
)
);

public $hasAndBelongsToMany = array(
'Evidence' => array(
'className' => 'Evidence',
'joinTable' => 'evidences_projects',
'foreignKey' => 'project_id',
'associationForeignKey' => 'evidence_id',
'unique' => 'keepExisting',
'conditions' => '',
'fields' => '',
'order' => '',
'limit' => '',
'offset' => '',
'finderQuery' => '',
),
'Remark' => array(
'className' => 'Remark',
'joinTable' => 'projects_remarks',
'foreignKey' => 'project_id',
'associationForeignKey' => 'remark_id',
'unique' => 'keepExisting',
'conditions' => '',
'fields' => '',
'order' => '',
'limit' => '',
'offset' => '',
'finderQuery' => '',
)
);
}

Evidence.php

App::uses('AppModel', 'Model');

class Evidence extends AppModel {

var $name = 'Evidence';
public $displayField = 'title';

public $validate = array(
'id' => array(
'notEmpty' => array(
'rule' => array('notEmpty'),
),
'numeric' => array(
'rule' => array('numeric'),
),
),
'title' => array(
'notEmpty' => array(
'rule' => array('notEmpty'),
),
),
'date' => array(
'datetime' => array(
'rule' => array('datetime'),
),
),
'sourcetype' => array(
'numeric' => array(
'rule' => array('numeric'),
),
),
'user_id' => array(
'numeric' => array(
'rule' => array('numeric'),
),
),
'created' => array(
'datetime' => array(
'rule' => array('datetime'),
),
),
);

public $belongsTo = array(
'User' => array(
'className' => 'User',
'foreignKey' => 'user_id',
'conditions' => '',
'fields' => '',
'order' => ''
)
);

public $hasMany = array(
'Remark' => array(
'className' => 'Remark',
'foreignKey' => 'evidence_id',
'dependent' => false,
'conditions' => '',
'fields' => '',
'order' => '',
'limit' => '',
'offset' => '',
'exclusive' => '',
'finderQuery' => '',
'counterQuery' => ''
),
);

public $hasAndBelongsToMany = array(
'Project' => array(
'className' => 'Project',
'joinTable' => 'evidences_projects',
'foreignKey' => 'evidence_id',
'associationForeignKey' => 'project_id',
'unique' => 'keepExisting',
'conditions' => '',
'fields' => '',
'order' => '',
'limit' => '',
'offset' => '',
'finderQuery' => '',
)
);
}

Remark.php

App::uses('AppModel', 'Model');

class Remark extends AppModel {

var $name = 'Remark';
public $displayField = 'title';

public $validate = array(
'id' => array(
'notEmpty' => array(
'rule' => array('notEmpty'),
),
'numeric' => array(
'rule' => array('numeric'),
),
),
'evidence_id' => array(
'numeric' => array(
'rule' => array('numeric'),
),
),
'created' => array(
'datetime' => array(
'rule' => array('datetime'),
),
),
);

public $hasAndBelongsToMany = array(
'User' => array(
'className' => 'User',
'joinTable' => 'users_remarks',
'foreignKey' => 'remark_id',
'associationForeignKey' => 'user_id',
'unique' => 'keepExisting',
'conditions' => '',
'fields' => '',
'order' => '',
'limit' => '',
'offset' => '',
'finderQuery' => '',
),
'Project' => array(
'className' => 'Project',
'joinTable' => 'projects_remarks',
'foreignKey' => 'remark_id',
'associationForeignKey' => 'project_id',
'unique' => 'keepExisting',
'conditions' => '',
'fields' => '',
'order' => '',
'limit' => '',
'offset' => '',
'finderQuery' => '',
)
);

public $belongsTo = array(
'Evidence' => array(
'className' => 'Evidence',
'foreignKey' => 'evidence_id',
'conditions' => '',
'fields' => '',
'order' => ''
)
);
}

User.php

App::uses('AppModel', 'Model');

class User extends AppModel {

var $name = 'User';
public $displayField = 'title';

public $validate = array(
'id' => array(
'notEmpty' => array(
'rule' => array('notEmpty'),
),
'numeric' => array(
'rule' => array('numeric'),
),
),
'username' => array(
'notEmpty' => array(
'rule' => array('notEmpty'),
),
),
'password' => array(
'notEmpty' => array(
'rule' => array('notEmpty'),
),
),
'full_name' => array(
'notEmpty' => array(
'rule' => array('notEmpty'),
),
),
'type' => array(
'numeric' => array(
'rule' => array('numeric'),
),
),
'created' => array(
'datetime' => array(
'rule' => array('datetime'),
),
),
);

public $hasMany = array(
'Evidence' => array(
'className' => 'Evidence',
'foreignKey' => 'user_id',
'dependent' => false,
'conditions' => '',
'fields' => '',
'order' => '',
'limit' => '',
'offset' => '',
'exclusive' => '',
'finderQuery' => '',
'counterQuery' => ''
),
'Project' => array(
'className' => 'Project',
'foreignKey' => 'user_id',
'dependent' => false,
'conditions' => '',
'fields' => '',
'order' => '',
'limit' => '',
'offset' => '',
'exclusive' => '',
'finderQuery' => '',
'counterQuery' => ''
)
);

public $hasAndBelongsToMany = array(
'Remark' => array(
'className' => 'Remark',
'joinTable' => 'users_remarks',
'foreignKey' => 'user_id',
'associationForeignKey' => 'remark_id',
'unique' => 'keepExisting',
'conditions' => '',
'fields' => '',
'order' => '',
'limit' => '',
'offset' => '',
'finderQuery' => '',
)
);
}

EvidencesController.php

class EvidencesController extends AppController{
public $components = array('Session');
var $helpers = array( 'Form' );

public function add(){
$projectid  = isset($this->request->query['projectid']) ? $this->request->query['projectid']    :null;
$projectData = $this->Evidence->Project->findById($projectid);
$this->set('project',$projectData);
if($this->request->is('post')){
$this->Evidence->create();
$this->request->data['Evidence']['user_id'] = Authcomponent::user('id');
if($this->Evidence->saveAll($this->request->data)){
$this->Session->setFlash('The Evidence has been created');
//$this->redirect(array('controller' => 'projects', 'action'=> 'view', $projectid));
print_r($this->request->data);
}
}
}
}

Я закомментировал редирект, чтобы я мог видеть массив печатных данных.

add.ctp

<h1>Create Evidence for <?php echo $this->Html->link($project['Project']['title'], array('controller' => 'projects', 'action'=> 'view',$project['Project']['id'])); ?></h1>
<?php
echo $this->Form->create('Evidence');
echo $this->Form->input('title');
echo $this->Form->input('date');
echo $this->Form->input('description');
echo $this->Form->input('sourcetype');
echo $this->Form->input('source');
echo $this->Form->input('pdfloc');
echo $this->Form->input('author');
echo $this->Form->input('authorcred');
echo $this->Form->input('Remark.remark');
echo $this->Form->input('Project.id', array('type' => 'hidden', 'value' => $project['Project']['id']));
echo $this->Form->end('Add Evidence');
?>

Это массив, который печатается из EvidencesController.php

Array ( [Evidence] => Array ( [title] => EvTestTile [date] => Array ( [month] => 01 [day] => 25 [year] => 2015 [hour] => 09 [min] => 45 [meridian] => am ) [description] => EvTestDescription [sourcetype] => 1 [source] => EvTestSource [pdfloc] => EvTestPdfloc [author] => EvTestAuthor [authorcred] => EvTestAuthorcred [user_id] => 1 ) [Remark] => Array ( [remark] => ReTestRemark ) [Project] => Array ( [id] => 2 ) )

Все остальные ассоциации с проектами, доказательствами и пользователями работают. Как мне получить данные из замечаний, чтобы сохранить их в соответствующей ассоциации?

Любая помощь будет принята с благодарностью!

0

Решение

Вы переопределены Свойства $ hasAndBelongsToMany в модели проекта (также в Remark.php).

Пытаться:

public $hasAndBelongsToMany = array(
'Evidence' => array(
'className' => 'Evidence',
'joinTable' => 'evidences_projects',
'foreignKey' => 'project_id',
'associationForeignKey' => 'evidence_id',
'unique' => 'keepExisting',
'conditions' => '',
'fields' => '',
'order' => '',
'limit' => '',
'offset' => '',
'finderQuery' => '',
),
'Project' => array(
'className' => 'Project',
'joinTable' => 'evidences_projects',
'foreignKey' => 'evidence_id',
'associationForeignKey' => 'project_id',
'unique' => 'keepExisting',
'conditions' => '',
'fields' => '',
'order' => '',
'limit' => '',
'offset' => '',
'finderQuery' => '',
)
);
0

Другие решения

Я должен был нарезать массив, чтобы получить результаты, которые я хотел, вот мой код:

EvidencesController.php

public function add(){
$projectid  = isset($this->request->query['projectid']) ? $this->request->query['projectid']    :null;
$projectData = $this->Evidence->Project->findById($projectid);
$this->set('project',$projectData);
$userData = $this->Evidence->User->findById(Authcomponent::user('id'));
$this->set('user',$userData);
if($this->request->is('post')){
$this->Evidence->create();
$this->request->data['Evidence']['user_id'] = Authcomponent::user('id');
$RemarksArray = array_slice($this->request->data, 1);
$EvidenceArray1 = array_slice($this->request->data, 0,1);
$EvidenceArray2 = array_slice($this->request->data, 2);
$EvidenceArray = array_merge($EvidenceArray1,$EvidenceArray2);

if($this->Evidence->saveAll($EvidenceArray)){
$RemarksArray1 = array_slice($this->request->data, 1);
$RemarksArray = array_merge($RemarksArray1,array('Evidence'=>array('id'=>$this->Evidence->getLastInsertId())));
if(strlen(trim($this->request->data['Remark']['remark'])) >0){
$this->Evidence->Remark->saveAll($RemarksArray);
}
$this->Session->setFlash('The Evidence has been created With Remark length: '.strlen(trim($this->request->data['Remark']['remark'])));
$this->redirect(array('controller' => 'projects', 'action'=> 'view', $projectid));
}
}
}

Не уверен, что это лучшие практики, но я работаю на меня.

0