CakePHP: created and modified fields not updating in join table - php

We have two models which are related by a has and belongs to many (HABTM) relationship: Jobs, Tests. We are able to add/edit the relationships successfully (we know because they show up in the join table), but their created and modified fields are never set.
Here are the model relationships:
//Job.php
public $hasAndBelongsToMany = array (
'Test' => array (
'classname' => 'Test',
'foreignKey'=>'job_id',
'joinTable' => 'jobs_tests',
'associatedForeignKey' => 'test_id'
)
);
//Test.php
public $hasAndBelongsToMany = array(
'Job' => array(
'className'=> 'Job',
'joinTable'=>'jobs_tests',
'foreignKey' => 'test_id',
'associatedForeignKey'=> 'job_id'
)
);
Here is the /view/Jobs/edit.ctp
echo $this->Form->select('Test', $test_options, array('class'=>'form-control', 'multiple'=>'checkbox'));
//This is always empty (nothing selected/checked).
Here is how we update in the controller...
if ($this->request->isPut() ) {
$data = $this->request->data;
$save = $this->Job->save( $data );
if ($save) {
$this->Session->setFlash('Job edited');
} else {
$this->Session->setFlash('Error editing job');
}
}
The records in the join table are correct but created and modified are always NULL.
What are we doing wrong?

I dont't think that cake fills created and modified even in HABTM join table. (I tried in one project of mine and it didn't work too but maybe it can be activated somwhow)
However if you don't set unique to true in your association array the records are deleted and re-created on every update, so the update field has no meaning here.
If you really want the two fields then you have to use the Has Many Trough relationship.

Related

Print all values of an array in CDetailView Yii

I'm currently new to Yii and have some problems in my app.
I have 2 AR (Employee and Children) with the relations is Employee has_many Children. Now when we go into the view of Employee (in the view&id=blablabla not in index), I want to list all the children that the Employee have.
I have made a function in EmployeeController class to retrieve the children from my db
$anak = Anak::Model()->findAll(array(
'condition'=>'id_karyawan=:id_karyawan',
'params'=>array(':id_karyawan'=>$id_karyawan)));
//return $anak;
foreach ($anak as $data){
return $data->namaanak;
}
the problem is, it only showing 1 data (the first one, to be exact) of the children, even though in my db the Employee has 3 children. When I try to count of query result, it's showing 3.
My employee/view is like this
$this->widget('zii.widgets.CDetailView', array(
'data'=>$model,
'attributes'=>array(
'id_karyawan',
'nama',
array(
'name'=>'idjabatan',
'value'=>$model->findByPk($model->id_karyawan)->jabatan->namajabatan,
),
array(
'name'=>'gaji',
'value'=>Yii::app()->numberFormatter->formatCurrency($model->findByPk($model->id_karyawan)->jabatan->gaji, 'Rp'),
),
'alamat',
array(
'name'=>'ttl',
'value'=>$model->tempatlahir.', '.Yii::app()->dateFormatter->format("dd MMMM yyyy", $model->tgllahir),
),
array(
'name'=>'Istri',
'value'=>Istri::model()->getNama($model->id_karyawan),
'type'=>'raw'
),
array(
'name'=>'Anak',
'value'=>$this->getAnak($model->id_karyawan),
'type'=>'raw'
)
),
I have tried to google it, but i couldn't find any working answer :(
PS: karyawan = employee, anak = children.
You are only getting the first related value because you are returning it right away inside your foreach loop in the function. Gather all the related models first then return that and work with that data.
You can also skip that extra function inside your controller. If you use Gii, it should have already set up the proper Employee HAS_MANY children relation for you, so you could use that to pull all related models for each Employee model you are looking at. See below for a quick example
Employee model:
public function relations()
{
return array(
'children' => array(self::HAS_MANY, 'Child', 'employee_id'),
);
}
View file, passing an employee model to CDetailView:
$this->widget('zii.widgets.CDetailView', array(
'data' => $model,
'attributes'=>array(
array(
'name' => 'Children',
'value' => function ($data) {
// Get all related children using the relation defined in the Employee model and use CHtml::listData to store data inside the $children variable as an array using `id` as key and `child_name` as value
$children = CHtml::listData($data->children, 'id', 'child_name');
// Return names as a comma separated list
return implode(', ', $children);
},
'type'=>'raw'
)
)
);
My tables/column names probably don't match up with what you have but hopefully this helps.

updating related tables in cake

I have this:
$this->request->data['Person']['person_id'] = $this->Session->read('insertedPersonID');
$savedPerson = $this->Person->saveAll($this->request->data, array('validate'=>'first'));
which updates the selected person row fine however its related tables like PersonColor and PersonParts are not updating, instead inserting new rows.
I thought cake automatically updates the related tables as well as long as the id of the main table which is the foreign key for the other two tables are provided since doing this:
$savedPerson = $this->Person->saveAll($this->request->data, array('validate'=>'first'));
inserts to the Person table and the other two related two tables fine.
How do I make it update the other two tables as well?
Edit:
For the model relations:
Person Model:
public $hasMany = array(
'PersonParts' => array(
'className' => 'Part',
'foreignKey' => 'part_person_id'
),
'PersonColors' => array(
'className' => 'Color',
'foreignKey' => 'color_person_id'
)
);
Part Model:
public $belongsTo = array(
'PartPerson' => array(
'className' => 'Person',
'foreignKey' => 'part_person_id'
)
);
Color Model:
public $belongsTo = array(
'ColorPerson' => array(
'className' => 'Person',
'foreignKey' => 'color_person_id',
'conditions' => '',
'fields' => '',
'order' => ''
)
);
edit 2
var_dump of $this->request->data
array(3){
["Person"]=>array(4){
["person_user_id"]=>string(1)"3"
["person_name"]=>string(9)"Britney"
["person_category_id"]=>string(2)"16"
["visibility"]=>string(1)"1"
["person_id"]=>string(1)"71"
}
["PersonParts"]=>array(1){
[0]=>array(3){
["part_name"]=>string(4)"hands"
["quantity"]=>string(1)"2"
["part_part_type_id"]=>string(1)"1"
}
}
["PersonColors"]=>array(2){
[0]=>array(4){
["color_name"]=>string(3)"blue"
["test_field1"]=>string(1)"8"
["test_field2"]=>string(1)"9"
["position"]=>int(1)
}
[1]=>array(2){
["color_name"]=>string(5)"red"
["position"]=>int(2)
}
}
}
Note: This var_dump is only showing ["person_id"]=>string(1)"71" under Person array as the added field to make cake do an update, not insert... person_id is not showing under the PersonParts and PersonColors here since it's not working that way. What should I pass or How should I do an update on the other 2 related tables?
To make Cake do an update on the related tables, you do need to pass in the id of the related record, otherwise Cake won't know which record to update.
You can make this a hidden field in your form, which is how I do things.
The var dump for PersonParts should look like this (note the extra 'part_id' field):
["PersonParts"]=>array(1){
[0]=>array(3){
["part_id"]=>string(1)"7"
["part_name"]=>string(4)"hands"
["quantity"]=>string(1)"2"
["part_part_type_id"]=>string(1)"1"
}
}
If you don't pass the id, then (from memory) Cake will delete the existing related records, and add new ones.

Multiple M2M in DataMapper ORM issue

I am building a small core piece for my DataMapper ORM library in CodeIgniter to control user's access/edit rights (CRUD) over DataMapper objects itself. For this I want to link a DataMapper Entity, Userrole and Userright together.
The documentation is here http://datamapper.wanwizard.eu/pages/advancedrelations.html (Under head; Multi-table Relationships).
So if I fill in the join table by hand I can just get the values without any problems. The only problem is saving the relationship.
Here are my Model-rules
Userrole
var $has_many = array(
'userright' => array(
'join_table' => 'dm_entities_userrights_userroles',
),
'dm_entity' => array(
'join_table' => 'dm_entities_userrights_userroles',
),
);
Userright
var $has_many = array(
'dm_entity' => array(
'join_table' => 'dm_entities_userrights_userroles',
),
'userrole' => array(
'join_table' => 'dm_entities_userrights_userroles',
),
);
Dm_entity
var $has_many = array(
'userrole' => array(
'join_table' => 'dm_entities_userrights_userroles',
),
'userright' => array(
'join_table' => 'dm_entities_userrights_userroles',
),
);
It seems odd I declared the table twice constantly, but it seems not to work if I don't.
So here's my retrieval code for this relation form the perspective of the Userright;
$userrole = new Userrole;
$userrole->get_where(array('name' => 'Administrator'));
$dm_entity = new Dm_entity;
$dm_entity->get_where(array('name' => 'User'));
$userrights = new Userright;
$userrights->where_related($userrole);
$userrights->where_related($dm_entity)->get();
$output = '';
foreach ($userrights as $userright) {
$output .= '<i><b>'.$userright->name.'</b></i> and ';
}
$output = substr($output, 0, -5);
echo '<b>'.$userrole->name.'</b> has the right to '.$output.' the DataMapper entity <b>'.$dm_entity->name.'</b>.'.br();
So this works without any problems either. But now the saving part:
$new_userright = new Userright;
$new_userright->get_where(array('name' => 'Update'));
$new_userright->save(array($userrole, $dm_entity));
Which results in two entries in the dm_entities_userrights_userroles table where 1 entry has dm_entity_id empty and the other the userrole_id empty.
I hope to avoid making a separate Model for the join table to solve this.
Does anyone know how I can get this to work so it makes one correct entry, instead of two scattered ones?
This is not going to work (as you have noticed).
A relation is between two models, and for each Many to Many relation you need a separate join table.
Although technically you can create a join table with 10 FK's to 10 different models, Datamapper will not be aware of that, and will treat the table as different for every relation, causing duplicates to appear.
The only way to make this work, is to define a model for the join table too, and give that one-to-many relations to each of the other models. You can then use that model to manually add relations by assigning or updating the FK values, and still use the many-to-many relations for retrieval and update.

Getting All groups that belong to user

I have HABTM for Users and Groups. I want to show in a Group view - all the Groups that belong to a User. Or to put it differently - all the Groups that have the User.
I am getting tangled in the MVC and am not able to figure it out. Here are my two models:
class Course extends AppModel
public $name = 'Course';
public $hasAndBelongsToMany = array('User' =>
array(
'unique' => false
)
);
And...
public $name = 'User';
public $hasAndBelongsToMany = array('Course' =>
array(
'unique' => true
)
);
The table name in the database is courses_users - this table houses group ids and user ids.
Should be simple enough but I'm new to CakePHP so I'd love some help. Thank you!
CakePHP has recursive set to 1 by default, which means that assuming you have not changed the recursive setting, it will automatically fetch all associated courses when you call find on a user, assuming you set up the HABTM relationship when doing the find. Therefore, all you have to do is:
$this->User->find('first', array('conditions' => array('User.id' => $this->Auth->user('id'))));
In your User model, I don't think it's strictly necessary, but I like to specify the join table and such on HABTM relationships:
public $hasAndBelongsToMany = array('Course' =>
array(
'unique' => true,
'dependent' => false,
'joinTable' => 'courses_users',
'foreignKey' => 'user_id',
'associationForeignKey' => 'course_id',
)
);
Keep in mind that in HABTM relationships, you don't ever really touch the joinTable beyond specifying which table to use as the joinTable when setting up the relationship. CakePHP will automatically do the rest of the work.

CakePHP/Croogo: A veeery complex association

When I was working on my current project, I ran into a rather complex issue. I'll point out my problem much more detailed right now:
There are three Models: User, UsersExtendedField and UsersExtended.
UsersExtendedField contains custom fields that can be managed manually. All custom fields can be shown in the Users view as well, and be filled out of course. The values are then stored in UsersExtended, which has got two foreignKeys: user_id and field_id.
The relations look like this: User hasMany UsersExtendedField, UsersExtendedField hasMany UsersExtended, UsersExtended belongsTo User, UsersExtendedField.
The problem: When accessing the Users view, a form with user information input is shown. Any UsersExtendedFields are available as well, and since these hasMany UsersExtended, they've got plenty of UsersExtended values. But I want to reduce those to only the value(s) that belong to the User, whose view is shown at the moment. Here are my (desired) relations:
Croogo::hookBehavior('User', 'Crooboard.ExtendedUser', array(
'relationship' => array(
'hasMany' => array(
'UsersExtendedField' => array(
'className' => 'Crooboard.UsersExtendedField',
'foreignKey' => '',
'conditions' => array('status' => 1)
),
),
),
));
class UsersExtendedField extends AppModel {
var $name = 'UsersExtendedField';
var $displayField = 'fieldname';
var $hasMany = array(
'UsersExtended' => array(
'className' => 'Crooboard.UsersExtended',
'foreignKey' => 'field_id',
'conditions' => array(
'UsersExtended.user_id = User.id'
)
),
);
}
This is not the full code, these are the important parts. The problem starts right where I wrote 'UsersExtended.user_id = User.id'. Obviously, this won't work. But I do not have any idea how to access the User.id here. I also could not imagine a HABTM structure to solve this task. Do you have any idea how to get the semantics of this 'UsersExtended.user_id = User.id' to work?
Thank your very much for taking the time to read through this and helping me!
It sounds like you need to set up your HABTM relationship properly.
You already have the join table, UsersExtended, which contains your foreign keys.
Remove all previous relationships and set up HABTM in each of your User and UserExtendedField models.
The relationship code in your User model would look like this:
var $hasAndBelongsToMany = array(
'UsersExtended' => array(
'className' => 'UsersExtended',
'joinTable' => 'UsersExtended', //assuming this is the
//name of that model's table
'foreignKey' => 'user_id',
'associationForeignKey' => 'field_id'
)
);
For more information check out the page in the cakephp book
In addition, this blog post helped me grasp the relationship concepts when I was learning cakephp.

Categories