I'm really struggling with a table association in cakephp, all I'm trying to do is associate two tables together, however one table has two two foreign keys to the other table.
For some reason, I cannot get any information to be displayed in the field select form for home_id ....
Please see the database picture below and the associated code.
I'm really new to cakephp but feel if I can nail this it will be really useful - any help is greatly appreciated.
Database Schema
class SafcTeam extends AppModel {
var $name = 'SafcTeam';
var $displayField = 'name';
var $validate = array(
'name' => array(
'notempty' => array(
'rule' => array('notempty'),
),
),
'badge' => array(
'notempty' => array(
'rule' => array('notempty'),
),
),
);
var $hasMany = array(
'SafcTeam' => array(
'className' => 'SafcEvent',
'foreignKey' => 'home_id',
)
);
}
class SafcEvent extends AppModel {
var $name = 'SafcEvent';
var $displayField = 'id';
var $validate = array(
'safc_matchtype_id' => array(
'numeric' => array(
'rule' => array('numeric'),
),
),
'safc_league_id' => array(
'numeric' => array(
'rule' => array('numeric'),
),
),
'home_id' => array(
'numeric' => array(
'rule' => array('numeric'),
),
),
'away_id' => array(
'numeric' => array(
'rule' => array('numeric'),
),
),
'streamer_id' => array(
'numeric' => array(
'rule' => array('numeric'),
),
),
'safc_channel_id' => array(
'numeric' => array(
'rule' => array('numeric'),
),
),
'comments' => array(
'notempty' => array(
'rule' => array('notempty'),
),
),
'safc_profile_id' => array(
'numeric' => array(
'rule' => array('numeric'),
),
),
'safc_source_id' => array(
'numeric' => array(
'rule' => array('numeric'),
),
),
'event_info_url' => array(
'notempty' => array(
'rule' => array('notempty'),
),
),
);
var $belongsTo = array(
'SafcMatchtype' => array(
'className' => 'SafcMatchtype',
'foreignKey' => 'safc_matchtype_id'
),
'SafcLeague' => array(
'className' => 'SafcLeague',
'foreignKey' => 'safc_league_id'
),
'SafcChannel' => array(
'className' => 'SafcChannel',
'foreignKey' => 'safc_channel_id'
),
'SafcProfile' => array(
'className' => 'SafcProfile',
'foreignKey' => 'safc_profile_id'
),
'SafcSource' => array(
'className' => 'SafcSource',
'foreignKey' => 'safc_source_id'
),
'SafcTeam' => array(
'className' => 'SafcTeam',
'foreignKey' => 'home_id'
)
);
}
you have to use an alias for each of this relation of your SafcTeam Model:
var $belongsTo = array(
//relationship for your home_id fk
'SafcHomeTeam' => array(
'className' => 'SafcTeam',
'foreignKey' => 'home_id'
),
//relationship for your away_id key
'SafcAwayTeam' => array(
'className' => 'SafcTeam',
'foreignKey' => 'away_id'
)
);
and also in the related safc team model :
var $hasMany = array(
'SafcHomeTeam' => array(
'className' => 'SafcEvent',
'foreignKey' => 'home_id',
),
'SafcAwayTeam' => array(
'className' => 'SafcEvent',
'foreignKey' => 'away_id',
)
);
In your SafcEvents controller in the action add and edit add this:
//to respect cake conventions need the select list to be plural (Teams <--- with a s at the end)
$safcHomeTeams = $this->SafcEvent->SafcHomeTeam->find('list');
$safcAwayTeams = $this->SafcEvent->SafcAwayTeam->find('list');
//also pass those list to the view
$this->set(compact('SafcAwayTeams', 'SafcHomeTeams));
In the safcevent view Add and Edit
in the form section :
//to respect cake convention to construct your select input properly
//you need to refere to the list established in the controller ($SafcHomeTeams by using $SafcHomeTeam_id <--singular + "_" + "id")
echo $this->Form->input('SafcAwayTeam_id');
echo $this->Form->input('SafcHomeTeam_id');
Cake does not support complex FK out the box, you can define a relation with conditions like so
public $hasMany = array(
'TheRelation' => array(
'foreignKey' => false,
'conditions' => array(
... conditions ...
)
)
)
Related
I'm trying to do this with last 2.x CakePHP version
http://i.stack.imgur.com/IylLu.png
Without education_id in projects_students table works perfectly. But doesn't work with education_id.
this is my implementation with education_id:
ProjectsStudent.php
class ProjectsStudent extends AppModel {
public $belongsTo = array(
'Project' => array(
'className' => 'Project',
'foreignKey' => 'project_id'
),
'Student' => array(
'className' => 'Student',
'foreignKey' => 'student_id'
)
);
Student.php
public $hasMany = array('ProjectsStudent');
public $hasAndBelongsToMany = array(
'Education' => array(
'className' => 'Student',
'joinTable' => 'projects_students',
'foreignKey' => 'student_id',
'associationForeignKey' => 'project_id',
),
);
Project.php
public $belongsTo = 'Status';
public $hasMany = array(
'Doc' => array(
'className' => 'Doc',
'joinTable' => 'docs',
'foreignKey' => 'project_id',
),
'History' => array(
'className' => 'History',
'joinTable' => 'history',
'foreignKey' => 'project_id',
),
'ProjectsStudent'
);
public $hasAndBelongsToMany = array(
'Student' => array(
'className' => 'Student',
'joinTable' => 'projects_students',
'foreignKey' => 'project_id',
'associationForeignKey' => 'student_id',
),
'Professor' => array(
'className' => 'Professor',
'joinTable' => 'projects_professors',
'foreignKey' => 'project_id',
'associationForeignKey' => 'professor_id',
),
'Education' => array(
'className' => 'Education',
'joinTable' => 'projects_educations',
'foreignKey' => 'project_id',
'associationForeignKey' => 'education_id',
),
);
ProjectsController.php
$data = array(
'Project' => array(
'id' => $id,
'status_id' => 5,
'Student' => array($this->Auth->user('id'))),
'History' => array(
array(
'action' => 'update -> status 5',
'student_id' => $this->Auth->user('id'),
)
),
'ProjectsStudent' => array(array(
'education_id' => "5"))
);
$this->Project->saveAll($data, array('deep' => true))
Output error:
Error: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '109' for key 'PRIMARY'
SQL Query: INSERT INTO tfg.projects_students (project_id, education_id) VALUES (109, 5)
I think CakePHP is trying 2 inserts, with (project_id, student_id) and with (project_id, education_id)
I want just one input like INSERT INTO tfg.projects_students (project_id,student_id,education_id) VALUES (109, 1, 5)
Thanks in advance, sorry for my english.
---SOLUTION---
$data = array(
'Project' => array(
'id' => $id,
'status_id' => 5,
'Student' => array($this->Auth->user('id'))),
'History' => array(
array(
'action' => 'update -> status 5',
'student_id' => $this->Auth->user('id'),
)
),
);
$this->Project->saveAll($data, array('deep' => true));
$this->Project->ProjectsStudent->updateAll(
array('education_id' => $this->Auth->user('education')),
array('project_id' => $this->Project->id));
You appear to have setup the projects_students table to use project_id as the primary key. The primary key needs to be unique whereas the project_id foreign key is likely to be duplicated (as appears to be happening for you). The join table should be at least:-
id (int)
project_id (int)
student_id (int)
Where id is the primary key (with auto increment enabled).
I have to fetch data from posts table
which has foreign keys (
category_id references to categories.id
created_by references to users.id,
updated_by references to users.id
)
I can fetch created_by username but not both
$this->Post->Behaviors->load('Containable');
$this->paginate = array(
'conditions' => array('Post.category_id' => $id),
'order' => array('title'),
'contain' => array(
'User'=>array(
'fields'=>array('id','first_name','last_name','username'),
'conditions' => array('User.id = Post.created_by')
),
//posts table has 2 fields(created_by & updated_by) associated with users table
//'User'=>array(
// 'fields'=>array('id','first_name','last_name','username'),
// 'conditions' => array('User.id = Post.updated_by')
// ),
'Category'=>array(
'Type'=>array(
'fields'=>array('id','type_name')
)
),
)
);
//post model
public $belongsTo = array(
'User'=> array(
'className' => 'User',
'foreignKey' => 'created_by',
'foreignKey' => 'updated_by'
),
);
//user model
public $hasMany = array(
'Post' => array(
'className' => 'Post',
'foreignKey' => array('created_by','updated_by'),
),
);
how to show both and alias both Users as (created_by & updated_by)
First you need to define two relationships in the Post model
public $belongsTo = array(
'CreatedUser'=> array(
'className' => 'User',
'foreignKey' => 'created_by'
),
'UpdatedUser'=> array(
'className' => 'User',
'foreignKey' => 'updated_by'
)
);
Now create the converse relationships in the User model.
public $hasMany = array(
'CreatedPosts' => array(
'className' => 'Post',
'foreignKey' =>'created_by'
),
'UpdatedPosts' => array(
'className' => 'Post',
'foreignKey' => 'updated_by'
),
);
Then the find()
$this->Post->Behaviors->load('Containable');
$this->paginate = array(
'conditions' => array('Post.category_id' => $id),
'order' => array('title'),
'contain' => array(
'CreatedUser'=>array(
'fields'=>array('id','first_name','last_name','username')
),
'UpdatedUser'=>array(
'fields'=>array('id','first_name','last_name','username')
),
'Category'=>array(
'Type'=>array(
'fields'=>array('id','type_name')
)
),
)
);
I have the following code that gives an error from the moment I do a find condition on the associated Model (HABTM):
class Users extends Model{
public $useTable = 'users';
public $hasAndBelongsToMany = array(
'UserCategories' => array(
'className' => 'UserCategories',
'joinTable' => 'user_categories_link',
'foreignKey' => 'user_id',
'associationForeignKey' => 'category_id',
'unique' => false,
)
);
public function getData($page = 0, $category = '', $subcategory = ''){
return $this->find('all', array(
'limit' => 6,
'page' => $page,
'conditions'=> array(
'active'=> 1,
'UserCategories.category_name' => $category, // THIS GIVES ERROR
'UserCategories.category_subcategory' => $subcategory, // THIS GIVES ERROR
)
));
}
In my Controller:
$this->Users->getData(0, 'somemaincategory', 'somesubcategory');
I can't seem to do conditions on the related HABTM-Model (UserCategories in this case). I also tried to use 'contain' (with $actsAs), but then he stills gives me all the User data even if there is no Category linked with it. The Category array is in that case just blank.
Hope someone can help me.
Thanks in advance,
Aäron
Do a manual join. You can use this to do an actual inner join (contain will act as a left join). http://book.cakephp.org/2.0/en/models/associations-linking-models-together.html#joining-tables
$this->find('all',
array(
'conditions' => array(
'active' => 1,
),
'joins' => array(
array(
'table' => 'user_categories_link',
'alias' => 'UserCategoriesLink',
'type' => 'inner',
'conditions' => array(
'UserCategoriesLink.user_id = User.id'
),
),
array(
'table' => 'user_categories',
'alias' => 'UserCategories',
'type' => 'inner',
'conditions' => array(
'UserCategories.id = UserCategoriesLink.category_id',
'UserCategories.category_name' => $category,
'UserCategories.category_subcategory' => $subcategory,
),
)
),
)
);
So, I have this method where I save a model and its associated models. It has validation rules, but not on the fields that are causing the errors.
The data being passed to the save method is ok, the return of the save method using atomic = false is true on every field except two, that do not have any validation.
The saveAll/saveAssociated fails, and the return of $this->Model->validationErrors is the list of the fields that are not being validated as a empty array.
I already had searched for this on web and found a similar problem to mine here on StackOverflow, but the answer didn't solve my problem.
EDIT
The link to the problem similar to mine: CakePHP save failing with validation errors set but empty
EDIT 2
Here's the code. The rest of the models are ok, so I won't post it here.
**Add Method**
public function add() {
if ($this->request->is('post')) {
if(empty($this->request->data['User']['referer'])) {
$this->request->data['Partner']['status'] = 1;
$this->request->data['User']['group_id'] = 2;
$this->request->data['User']['status'] = 1;
$this->request->data['Customer']['birthday'] = implode("-", array_reverse(explode("/", $this->request->data['Customer']['birthday'])));
$this->request->data['Customer']['newsletter'] = ($this->request->data['Customer']['newsletter'] == "1") ? true : false;
$this->request->data['Customer']['accept'] = ($this->request->data['Customer']['accept'] == "1") ? true : false;
if(!$this->request->data['Customer']['accept']) {
$this->Session->setFlash(__('You must accept the terms and conditions to proceed.'), 'danger');
} else {
$this->Customer->Partner->create();
var_dump($this->Customer->Partner->saveAssociated($this->request->data, array('atomic' => false)));
debug($this->Customer->Partner->validationErrors);
exit();
if($this->Partner->saveAll($this->request->data)) {
$this->Session->setFlash(__('Your profile has been saved. Welcome to Abaixo da Tabela.'), 'success');
$this->redirect(array('controller' => 'pages', 'action' => 'display', 'home', 'admin' => false));
} else {
$this->Session->setFlash('Ocorreu um erro ao tentar salvar seu perfil. Verifique se os campos estão preenchidos corretamente e tenta novamente.', 'danger');
}
}
}
}
}
** Partner Model **
class Partner extends AppModel {
public $validate = array(
'person_type' => array(
'notEmpty' => array(
'rule' => array('notEmpty'),
),
),
'status' => array(
'numeric' => array(
'rule' => array('numeric'),
),
),
);
public $hasMany = array(
'Address' => array(
'className' => 'Address',
'foreignKey' => 'partner_id',
),
'Contact' => array(
'className' => 'Contact',
'foreignKey' => 'partner_id',
),
'Customer' => array(
'className' => 'Customer',
'foreignKey' => 'partner_id',
),
'User' => array(
'className' => 'User',
'foreignKey' => 'partner_id',
),
);
}
** Address Model **
class Address extends AppModel {
public $validate = array(
'partner_id' => array(
'numeric' => array(
'rule' => array('numeric'),
),
),
'address' => array(
'notEmpty' => array(
'rule' => array('notEmpty'),
),
),
'number' => array(
'notEmpty' => array(
'rule' => array('notEmpty'),
),
),
'zip' => array(
'notEmpty' => array(
'rule' => array('notEmpty'),
),
),
'district' => array(
'notEmpty' => array(
'rule' => array('notEmpty'),
),
),
'city_id' => array(
'numeric' => array(
'rule' => array('numeric'),
),
),
'uf' => array(
'notEmpty' => array(
'rule' => array('notEmpty'),
),
),
);
public $belongsTo = array(
'Partner' => array(
'className' => 'Partner',
'foreignKey' => 'partner_id',
),
'City' => array(
'className' => 'City',
'foreignKey' => 'city_id',
)
);
}
** Customer Model **
class Customer extends AppModel {
public $validate = array(
'partner_id' => array(
'numeric' => array(
'rule' => array('numeric'),
),
),
'birthday' => array(
'date' => array(
'rule' => array('date'),
),
),
);
public $belongsTo = array(
'Partner' => array(
'className' => 'Partner',
'foreignKey' => 'partner_id',
),
'City' => array(
'className' => 'City',
'foreignKey' => 'city_id',
)
);
}
** debug($this->Customer->Partner->validationErrors) **
array (size=5)
'Partner' => boolean true
'Address' =>
array (size=7)
'zip' => boolean true
'address' => boolean true
'number' => boolean true
'adjunct' => boolean false
'district' => boolean true
'uf' => boolean true
'city_id' => boolean true
'Contact' =>
array (size=3)
'email' => boolean true
'phone_1' => boolean true
'phone_2' => boolean true
'User' =>
array (size=5)
'username' => boolean true
'password' => boolean true
'password_confirm' => boolean true
'group_id' => boolean true
'status' => boolean true
'Customer' =>
array (size=4)
'genre' => boolean true
'birthday' => boolean true
'newsletter' => boolean false
'accept' => boolean true
Note the two false responses in the return of the save method.
(Answered by a question edit. Converted to a community wiki answer. See Question with no answers, but issue solved in the comments (or extended in chat) )
The OP wrote:
Turned out that the error was in the view. The form fields for the associated models were like:
echo $this->Form->input('Customer.birthday')
echo $this->Form->input('Customer.newsletter')
echo $this->Form->input('Customer.accept')
When the correct way was:
echo $this->Form->input('Customer.0.birthday')
echo $this->Form->input('Customer.0.newsletter')
echo $this->Form->input('Customer.0.accept')
As in the Book, the fields for models with the hasMany association need a index, in that case, the 0.
a post has a user (belongsTo) and a user has a profile (hasOne). Normally everything works: I can access from Post to User and from User to Profile.
From Post, all works using a generic Find. The result is more or less this (I deleted some keys, just for example):
array(
'Post' => array(
'id' => '1',
'category_id' => '1',
'user_id' => '1',
'title' => 'Example',
'text' => '',
),
'User' => array(
'password' => '*****',
'id' => '1',
'group_id' => '1',
'username' => 'mirko',
'status' => 'active',
'Profile' => array(
'id' => '1',
'user_id' => '1',
'first_name' => 'Mirko',
'last_name' => 'Pagliai',
),
)
)
The problem comes when I use "fields", when I want to extract only a few fields.
For example, this works:
'fields' => array('id', 'title', 'User.id')
and the result is:
array(
'Post' => array(
'id' => '1',
'title' => 'Articolo di prova :-)'
),
'User' => array(
'id' => '1'
)
)
But I don't understand, always using "fields", how to access Profile.
These don'yt work:
'fields' => array('id', 'title', 'User.id', 'Profile.id')
'fields' => array('id', 'title', 'User.id', 'User.Profile.id')
I always get this error "Error: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'User.Profile.id' in 'field list'".
What's wrong? Thanks.
EDIT:
I'm not using the Containable behavior. Maybe is this the problem? Is it essential in this case?
An example, using paginate:
$this->paginate = array(
'conditions' => $conditions,
'fields' => array('id', 'title', 'User.id', 'Profile.id'),
'limit' => 10,
'recursive' => 2,
);
EDIT2:
thanks to #Hoff, I am close to the solution. But there is still something wrong (and Containable is very useful!).
In AppModel.php I added:
...
class AppModel extends Model {
public $actsAs = array('Containable');
public $recursive = -1;
...
But this doesn't work:
$this->paginate = array(
'conditions' => $conditions,
'contain' => array(
'User' => array(
'fields' => array('id'),
'Profile' => array(
'fields' => array('id', 'full_name'),
),
),
'Category' => array(
'fields' => 'title',
),
),
'fields' => array('id', 'user_id', 'category_id', 'title', 'created', 'modified', 'published'),
'limit' => 10,
);
Cause I get:
array(
(int) 0 => array(
'Post' => array(
'id' => '1',
'user_id' => '1',
'category_id' => '1',
'title' => 'Articolo di prova :-)',
'created' => '2012-06-21 18:46:00',
'modified' => '0000-00-00 00:00:00',
'published' => true
),
'Category' => array(
'title' => 'prova',
'id' => '1'
),
'User' => array(
'id' => '1'
)
)
)
but if I add any field to User (email, username, password, etc.), this works:
'User' => array(
'fields' => array('id', 'username'),
'Profile' => array(
'fields' => array('id', 'full_name'),
),
),
And I get:
array(
(int) 0 => array(
'Post' => array(
'id' => '1',
'user_id' => '1',
'category_id' => '1',
'title' => 'Articolo di prova :-)',
'created' => '2012-06-21 18:46:00',
'modified' => '0000-00-00 00:00:00',
'published' => true
),
'Category' => array(
'title' => 'prova',
'id' => '1'
),
'User' => array(
'id' => '1',
'username' => 'mirko',
'Profile' => array(
'id' => '1',
'full_name' => 'Mirko Pagliai'
)
)
)
)
Instead of using the 'recursive' key, I highly suggest using the containable behavior. The documentation on the behavior can be found here. I would suggest applying the behavior in your AppModel so you don't need to add it to all your models. In Model/AppModel.php:
App::uses('Model', 'Model');
class AppModel extends Model {
public $actsAs = array('Containable');
public $recursive = -1;
}
Then, for your pagination:
$this->paginate = array(
'conditions' => $conditions,
'fields' => array('id', 'title'),
'limit' => 10,
'contain' => array(
'User' => array(
'fields' => array('id'),
'Profile' => array(
'fields' => array('id')
)
)
)
);