cant add new record in HABTM table - php

I want to add a new record in a table called TutorsSubject. This table is created from HABTM relationship of Tutor and Subject. Anyway I load the subject names in a text box and I can select a subject name but I cant add a new record. I need to set the id of the tutor_id.
There are 3 fields in the tutorsSubject table called id,tutor_id and subject_id. I only need to select in 1 field which is the subject_id from a list of names found in the subject table, and then set the tutor_id manually.
Currently I am able to select from a list of subject names but I cant add a new record with the subject name and set tutor_id.
Error: SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails
class TutorsSubjectsController extends AppController {
public function tutoradd() {
$this->loadModel('Subject');
$options['recursive']=-1;
$options['fields']=array('Subject.name');
$te2= $this->Subject->find('list',$options);
debug($te2);
$this->set( 'te',$te2);
//put is for edit and post for new record
if ($this->request->is('post')) {
$this->request->data['TutorsSubject']['tutor_id']=2;
debug($this->request->data);
if ($this->TutorsSubject->save($this->request->data)) {
$this->Session->setFlash(__('Your post has been updated.'));
return $this->redirect(array('controller' => 'tutors','action' => 'tutordetails'));
}
$this->Session->setFlash(__('Unable to update your post.'));
}
//View which works fine as it displays the list
echo $this->Form->create('TutorsSubject', array('type' => 'post'));
echo $this->Form->input('tutorsSubject.subject_id', array('options' => $te));
echo $this->Form->end('Save Post');
//model subject
public $hasAndBelongsToMany = array(
'Tutor' => array(
'className' => 'Tutor',
'joinTable' => 'tutors_subjects',
'foreignKey' => 'subject_id',
'associationForeignKey' => 'tutor_id',
'unique' => 'keepExisting',
'conditions' => '',
'fields' => '',
'order' => '',
'limit' => '',
'offset' => '',
'finderQuery' => '',
'deleteQuery' => '',
'insertQuery' => ''
)
);
//model tutor
public $hasAndBelongsToMany = array(
'Subject' => array(
'className' => 'Subject',
'joinTable' => 'tutors_subjects',
'foreignKey' => 'tutor_id',
'associationForeignKey' => 'subject_id',
'unique' => 'keepExisting',
'conditions' => '',
'fields' => '',
'order' => '',
'limit' => '',
'offset' => '',
'finderQuery' => '',
'deleteQuery' => '',
'insertQuery' => ''
),
);

Related

CakePHP - saving HABTM fails

I have tables that looks like this. Basically WarehousePlace can have many ItemType in it and ItemType can be used by many WarehousePlace. But when I try to save I get an database error:
Error: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'WarehousePlacesItemType.item_type_id' in 'field list'
SQL Query: SELECT `WarehousePlacesItemType`.`item_type_id` FROM `modules`.`warehouse_places_item_types` AS `WarehousePlacesItemType` WHERE `WarehousePlacesItemType`.`warehouse_place_id` = '22'
But everything is done by conventions and also debugged data is like it should be and I do not see what is wrong.
WarehousesController
public function add() {
$this->load();
if ($this->request->is('post')) {
$data = array(
'WarehousePlace' => array(
'name' => $this->request->data['WarehousePlace']['name'],
),
'ItemType' => array(
'ItemType' => $this->request->data['ItemType']['ItemType']
)
);
$this->WarehousePlace->create();
if ($this->WarehousePlace->saveAll($data, array('validate' => 'first', 'deep' => true))) {
//success
}
if ($this->WarehousePlace->validationErrors) {
//validation
} else {
//error
}
}
}
tables:
warehouse_places_item_types(warehouse_places_id,item_types_id) -> no primary key since CakePHP 2,
warehouse_places(id, name),
item_types(id, name)
Models:
ItemType
public $hasAndBelongsToMany = array(
'WarehousePlace' => array(
'className' => 'WarehousePlace',
'joinTable' => 'warehouse_places_item_types',
'foreignKey' => 'item_type_id',
'associationForeignKey' => 'warehouse_place_id',
'unique' => 'keepExisting',
)
);
WarehousePlace
public $hasAndBelongsToMany = array(
'ItemType' => array(
'className' => 'ItemType',
'joinTable' => 'warehouse_places_item_types',
'foreignKey' => 'warehouse_place_id',
'associationForeignKey' => 'item_type_id',
'unique' => 'keepExisting',
)
);

Cakephp. SQLSTATE[42S22]: Column not found: 1054 Unknown column 'CalendarsClassification.id' in 'field list'

When I delete a classification, I get this error
Error: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'CalendarsClassification.id' in 'field list'
SQL Query: SELECT `CalendarsClassification`.`id` FROM `calendars_classifications` AS `CalendarsClassification` WHERE `CalendarsClassification`.`calendar_id` = 221
CalendarsClassification.id does not exist, but I do not know how to change it.
ClassificationsController
public function delete($id = null) {
if (!$id) {
$this->flash(__('Invalid Classification', true), array('controller'=>'clients','action'=>'index'));
}
$this->request->data = $this->Classification->read(null, $id);
if ($this->Classification->delete($id, true)) {
$this->flash(__('Classificació esborrada.', true), array('controller'=>'blocks','action'=>'view',$this->data['Classification']['block_id']));
}
}
Model Classification
class Classification extends AppModel {
var $name = 'Classification';
var $validate = array(
'long_name' => array(
'rule' => array('minLength', 1)
)
);
//The Associations below have been created with all possible keys, those that are not needed can be removed
var $belongsTo = array(
'Block' => array('className' => 'Block',
'foreignKey' => 'block_id',
'conditions' => '',
'fields' => '',
'order' => ''
)
);
var $hasMany = array(
'Line' => array('className' => 'Line',
'foreignKey' => 'classification_id',
'conditions' => '',
'fields' => '',
'order' => '',
'limit' => '',
'offset' => '',
'dependent' => true,
'exclusive' => '',
'finderQuery' => '',
'counterQuery' => ''
)
);
var $hasAndBelongsToMany = array(
'Calendar' => array('className' => 'Calendar',
'joinTable' => 'calendars_classifications',
'foreignKey' => 'calendar_id',
'associationForeignKey'=> 'classification_id',
'conditions' => '',
'fields' => '',
'order' => '',
'limit' => '',
'unique' => true,
'finderQuery' => '',
'deleteQuery' => '',
)
);
}
if there is the field 'id' in the table and still you are unable to delete the row then you should clear the cache and then try to delete the row.
here is the path for cache:
\app\tmp\cache\models
and
\app\tmp\cache\persistent
Note: Do not delete the folder.
Hope this helps
i believe it should be "calendar_id" instead of "id".
As per the Query reflects.
SELECT CalendarsClassification.id FROM calendars_classifications AS CalendarsClassification WHERE CalendarsClassification.calendar_id = 221
If you're table doesn't have a column id then you need to define which column is the primary key in the relevant model. For example:-
class CalendarsClassification extends AppModel {
public $primaryKey = 'example_id';
}
The model delete() method uses the primary key as the first parameter to delete with so you must set the primaryKey for the model if it is different from Cake conventions before using this method.
You really should have a primary key for every model and it is advisable to stick with Cake conventions and name it id if possible as this will simplify your code significantly.
If you are not trying to delete a record by the primary key then you want to be using deleteAll() for which you can pass conditions for the deletion as the first parameter. Something like this:-
$this->CalendarsClassification->deleteAll(['example_id' => $id]);

how to fetch data from the two table with different foreign key names

I am new to cake php . Please be cool with me . I am trying to fetch the data from the two table ce_actionitems and ce_projects.
i want to fetch the data from action items . my model is
public $hasOne = array(
'Project' => array(
'className' => 'Project',
'foreignKey' => 'id',
'joinTable' => 'actionitems',
'unique' => 'keepExisting',
'associatedKey' => 'project_id',
'conditions' => '',
'fields' => '',
'order' => '',
'limit' => '',
'offset' => '',
'finderQuery' => '',
'deleteQuery' => '',
'insertQuery' => ''
)
);
but is is returning the null data because it is matching id in projects with id in action items. this is the generated query
LEFT JOIN EB.ce_projects AS Project ON (Project.id =
Actionitems.id)
but i want this to be
LEFT JOIN EB.ce_projects AS Project ON (Project.id =
Actionitems.project_id)
i got this working if i mention public $primaryKey = 'project_id'; in my Actionitems but then it stop inserting the action items.
any help will be appriciated.
mention 'project_id' as foreign key in Actionitems

Passing non-form data before save (CakePHP)

Course HasMany Lesson.
I am trying to save a lesson in a Course view, but want to automatically assign the current course_id without them having to select it.
How do I do that?
Here is my Courses view controller:
public function view($id = null) {
if (!$this->Course->exists($id)) {
throw new NotFoundException(__('Invalid course'));
}
$options = array('conditions' => array('Course.' . $this->Course->primaryKey => $id));
$this->set('course', $this->Course->find('first', $options));
//Adding Lesson from Course View
if ($this->request->is('post')) {
$this->Course->Lesson->create();
if ($this->Course->Lesson->save($this->request->data)) {
$this->Session->setFlash(__('The lesson has been saved.'), array ('class' => 'alert alert-success'));
return $this->redirect(array('controller'=> 'lessons', 'action' => 'view', $this->Course->Lesson->id));
} else {
$this->Session->setFlash(__('The lesson could not be saved. Please, try again.'), array ('class' => 'alert alert-danger'));
}
}
$courses = $this->Course->Lesson->Course->find('list');
$this->set(compact('courses'));
}
Currently, it's saving the lesson but not passing the course_id to the new lesson.
Lesson Model:
public $belongsTo = array(
'Course' => array(
'className' => 'Course',
'foreignKey' => 'course_id',
'conditions' => '',
'fields' => '',
'order' => ''
)
);
Course Model:
public $hasMany = array(
'Lesson' => array(
'className' => 'Lesson',
'foreignKey' => 'course_id',
'dependent' => false,
'conditions' => '',
'fields' => '',
'order' => '',
'limit' => '',
'offset' => '',
'exclusive' => '',
'finderQuery' => '',
'counterQuery' => ''
)
This is basically a duplicate of CakePHP: Securely setting a default value on a form.
Check my answer there or read the blog article I've wrote after that answer.

belongsTo relationship & filtering in cakePHP

I'm a newbie to cakePHP and I've taken on creating a very small "status reporting" project, that would allow a user to report their current status on a project that they were assigned on.
I'm currently using the acl, auth, and session components to allow for multiple tier users to manage one another with an admin creating users, projects, and assigning them to one another. I have also fixed it so that when a user is logged in and goes to add a "status" that their login session automatically takes care of the "user_id" for the status:
$this->data['Status']['user_id'] = $this->Auth->user('id');
What I need help doing now is filter the options for the project that the user can pick to add a "status" to.
I currently have a setup with a table that holds the relationships between users and projects named *projects_users* with *id, project_id, user_id* as fields. But, after baking this setup, when the user is adding a "status" the drop down menu provides all projects rather than strictly the ones they are "assigned to."
I would like to filter the user's options to the projects that they are assigned to. Is there considerable more relationships I should be setting up or is this a pretty easy little function to write? Any help would be greatly appreciated and if I have left out information, I'd be glad to post anything else.
Here is the Status Model setup:
class Status extends AppModel {
var $name = 'Status';
//The Associations below have been created with all possible keys, those that are not needed can be removed
var $belongsTo = array(
'User' => array(
'className' => 'User',
'foreignKey' => 'user_id',
'conditions' => '',
'fields' => '',
'order' => ''
),
'Project' => array(
'className' => 'Project',
'foreignKey' => 'project_id',
'conditions' => '',
'fields' => '',
'order' => ''
)
);
}
My User Model looks like this:
var $belongsTo = array(
'Group' => array(
'className' => 'Group',
'foreignKey' => 'group_id',
'conditions' => '',
'fields' => '',
'order' => ''
)
);
var $hasMany = array(
'Status' => array(
'className' => 'Status',
'foreignKey' => 'user_id',
'dependent' => false,
'conditions' => '',
'fields' => '',
'order' => '',
'limit' => '',
'offset' => '',
'exclusive' => '',
'finderQuery' => '',
'counterQuery' => ''
)
);
var $hasAndBelongsToMany = array(
'Project' => array(
'className' => 'Project',
'joinTable' => 'projects_users',
'foreignKey' => 'user_id',
'associationForeignKey' => 'project_id',
'unique' => true,
'conditions' => '',
'fields' => '',
'order' => '',
'limit' => '',
'offset' => '',
'finderQuery' => '',
'deleteQuery' => '',
'insertQuery' => ''
)
);
In the database, You should have a column called project_id in the user table that is associated with the project table's id column.
Then, in your User model, you should create a hasMany relationship with the Project model.
class User extends AppModel {
var $name = 'User';
var $hasMany = 'Project';
}
Now, when you fetch a particular user, you will get all projects that the user is associated with.

Categories