I've been digging through similar questions but couldn't get my app to save HABMT relationsships.
I want to have "Test" HABMT "Browser".
The Tables:
cake_browsers (id, name, ...)
cake_tests (id, name, ...)
cake_browsers_tests(browser_id, test_id)
The Relationsships that are already in the middle-table can be read.
The result of $this->Test->findById($id) is:
Array(
[Test] => Array
(
[id] => 94
[name] => NM Test 2
[description] =>
[created] => 2015-03-22 18:54:41
[modified] => 2015-03-22 19:53:28
)
[Browser] => Array
(
[0] => Array
(
[id] => 2
[name] => Firefox
[height] => 768
[width] => 1366
[active] => 1
)
)
)
The Model:
class Test extends AppModel {
public $actsAs = array('Containable');
public $hasAndBelongsToMany = array(
'Browser' => array(
'className' => 'Browser',
)
); ...
The controller-function:
public function add() {
$this->set('testDomains', $this->Test->DomainSchedule->TestDomain->find('all'));
$this->set('browsers', $this->Test->Browser->find('list'));
if ($this->request->is('post')) {
$this->Test->create();
$newTest = $this->request->data;
print "<pre>"; print_r($newTest); print "</pre>";
if ($this->Test->saveAll($newTest)) {
if($this->scheduleAutoTestRun($this->Test->id)){
$this->Session->setFlash(__('Your test has been saved. Additionally it has been added to the queue.'));
}else{
$this->Session->setFlash(__('Your test has been saved.'));
}
//return $this->redirect(array('action' => 'index'));
}else{
$this->Session->setFlash(__('Unable to add your test.'));
}
}
}
The View:
...
<?php echo $this->Form->input('Browser',array('multiple'=>'checkbox'));?>
...
The Content of $this->request->data
Array(
[Test] => Array
(
[name] => NM Test
[description] =>
)
[Browser] => Array
(
[Browser] => Array
(
[0] => 2
)
)
So, as far as I've been reading, I understand that this is the way it should look like. Unfortunately it is not saving the relationship that Browser with id=2 is connected to the new created Test.
Could anybody give me a hint what I am doing wrong?
Thanks!
I believe this needs the param deep as in $this->Test->saveAll( $data, array('deep' => true) )
Related
I have a Courses model that gives me this array:
[User] => Array
(
[0] => Array
(
[id] => 4
[username] => itaita
[password] => sdfasdgadgadfgsfdgsdgsdgsdgdsg
[email] => itaita#xyz.com
[name] =>
[role] => admin
[hash_change_password] =>
[created] => 2014-03-16 21:06:48
[modified] => 2014-03-16 21:06:48
[CoursesUser] => Array
(
[id] => 1
[user_id] => 4
[course_id] => 1
)
)
)
I want to create a subscribe/unsubscribe button that will delete the CoursesUser where id=this user id and course_id = this course but I don't know how to access it from the Courses controller and view.
Currently I have:
public function unsubscribe($id = null) {
$this->Course->id = $id;
$userid = CakeSession::read("Auth.User.id");
if (!$this->Course->exists()) {
throw new NotFoundException(__('Invalid course'));
}
$this->request->onlyAllow('post', 'delete');
if ($this->Course->User->delete(array('CoursesUser.user_id'=> $userid), false)) {
$this->Session->setFlash(__('The course has been deleted.'));
} else {
$this->Session->setFlash(__('The course could not be deleted. Please, try again.'));
}
return $this->redirect(array('action' => 'index'));
}
But this deletes the user.
I know the problem is here: $this->Course->User->delete but I don't know how to change this to address the CoursesUser array.
Help!
You could use this:
$this->Course->User->CoursesUser->deleteAll(array('CoursesUser.user_id' => $user_id, 'CoursesUser.course_id' => $id), false);
Basically, assuming that you have your model relations set up correctly, this will delete only the CoursesUser rows that match the user_id that you have retrieved from auth that also have the course_id supplied to the action.
I try to use CakePhp but i don't find the solution. Here is my problem :
I have 2 models ant i try to link it.
The First is Player (which mysql table is players)
The second is Toto (which mysql table is totos)
I have a field un players called toto_id
And in my model Player i wrote :
<?php
class Player extends AppModel {
public $validate = array(
'name' => array(
'rule' => 'notEmpty'
)
);
public $hasOne = 'Toto';
}
And in my controller PlayersController
class PlayersController extends AppController {
public $helpers = array('Html', 'Form', 'Session');
public $components = array('Session');
public function index() {
$params = array(
'order' => array("Player.firstname")
);
$a = $this->Player->find('all', $params);
print_r($a);
$this->set('liste', $a);
}
}
And my print_r displays
Array
(
[0] => Array
(
[Player] => Array
(
[id] => 2
[name] => DESMAISON
[firstname] => Christophe
[is_intern] => 1
[score] => 663
[created] => 2014-01-05
[modified] => 0000-00-00 00:00:00
[toto_id] => 2
)
)
[1] => Array
(
[Player] => Array
(
[id] => 10
[name] => CHARLERY
[firstname] => Daphné
[is_intern] => 1
[score] => 572
[created] => 2014-01-04
[modified] => 0000-00-00 00:00:00
[toto_id] => 0
)
)
I don't understand why in my array i haven't a reference to Toto. Someone can help me ?
Thank you for your help
Ps : i use cakephp 2.4.4 PHP 5.4.7
I think this is BelongsTo Association .
Instead of HasOne association try to use BelongsTo,
class Invoice extends AppModel {
public $belongsTo = array(
'Toto' => array(
'className' => 'Toto',
'foreignKey' => 'toto_id'
),
);
if you want to retrieve data from database you have to set your recursivity and there is two ways first one :
$players = $this->Player->find('all',array('recursive'=>2));
// or
$this->Player->recursive = 2;
$player = $this->Player->find('all');
I have two controllers: events and results. Events hasMany results, results belongsTo Events. I can save just fine, but when I go to edit, I can only get the information for the Event part of the form, to come in automagically.
I build the Results form info like this:
$option_number = 5;
for ($i = 0; $i < $option_number; $i++) {
echo $this->Form->select("Result.{$i}.object_id", $qual_options, array('empty' => false, 'class' => 'result-name'));
echo $this->Form->hidden("Result.{$i}.id");
echo $this->Form->hidden("Result.{$i}.type", array('value' => 'qual'));
echo $this->Form->hidden("Result.{$i}.action", array('value' => 'add')); ?>
}
In the backend, when I'm doing this to get the automagic population:
if ($this->request->is('get')) {
$this->request->data = $this->Event->findById($id);
}
It works just fine, but I can't figure out how to get it to show the Results. I've tried many things, most probable being:
$this->request->data['Result'] = $this->Result->findAllByEventId($id);
With that, I end up with a data structure like:
[Result] => Array
(
[0] => Array
(
[Result] => Array
(
[id] => 1
[object_id] => 1
[type] => qual
[action] => add
[amt] => 10
[event_id] => 1
)
)
[1] => Array
(
[Result] => Array
(
[id] => 2
[object_id] => 2
[type] => qual
[action] => add
[amt] => 1
[event_id] => 1
)
)
... etc.
)
)
Which definitely looks fishy, I just can't seem to manipulate it to work.
UPDATE I should have mentioned this; this is what my data looks like when I SAVE it, and I want to mimic this!
[Result] => Array
(
[0] => Array
(
[object_id] => 1
[type] => qual
[action] => add
[amt] => 0
[event_id] => 3
)
[1] => Array
(
[object_id] => 1
[type] => qual
[action] => add
[amt] => 1
[event_id] => 3
)
You can see that each numeric key after just has the information in it; instead, my numeric keys ALSO have an array INSIDE them name Result, and I have no idea how to make that go away properly! :} I could always loop through and build it in the format CakePHP wants, but I want to do it properly. And that single line above is what needs changing, but I have run out of ideas.
What about just using find('first') against the event? Since it's hasMany, it will return the Result model in a single [Result] key with many numeric keys.
$this->request->data = $this->Event->find('first', array(
'conditions' => array(
'Event.id' => $id
),
'contain' => array(
'Result'
)
));
This will return something like:
array(
'Event' => array(
'id' => 1,
'name' => 'event name'
),
'Result' => array(
0 => array(
'id' => 1,
...
),
1 => array(
'id' => 2,
...
)
)
);
You could unset the Event key if you needed to.
I have 3 users tables on my DB:
Users
users_twitter
users_web
Users is the parent of both users_twitter and users_web.
And then another table for comments. Both kind of users can comment.
So, when I want to show the comments I need to get information of the author of each comment.
In order to do this I am using the variable $belongsTo on the /Model/Comment.php like this:
public $belongsTo = array(
'users' => array(
'foreignKey' => 'idUser'
)
);
In Controller/CommentController, when i do this:
public function index($idPost) {
$this->Comment->recursive = 0;
return $this->Comment->find('all');
}
I get this kind of array:
[0] => Array
(
[Comment] => Array
(
[id] => 1
[idPost] => 441
[idUser] => 387371023
[comment] => hello word
[created] => 2012-03-01 00:00:00
)
[User] => Array
(
[id] => 1
[username] => myname
)
)
And what I want is to get more info yet, the one of the subtype of Users, depending on the existence of the ID on the subtype tables.
In case it was an id of a user_web table, I would like to get this:
[0] => Array
(
[Comment] => Array
(
[id] => 1
[idPost] => 441
[idUser] => 387371023
[comment] => hello word
[created] => 2012-03-01 00:00:00
)
[User] => Array
(
[id] => 1
[username] => myname
[users_web] => Array
(
[id] => 1
[username] => myName
[password] => XXXXX
[verified] => 1
[created] => 1
)
)
Do you know if that's possible with CakePHP?
As far as I know, with $hasOne I only get one level more, I need two.
In your AppModel add
public $actsAs = array('Containable');
In your index:
public function index($idPost) {
return $this->Comment->find('all', array(
'contain' => array('User.UsersWeb')));
}
Your User model has to be associated with a UsersWeb model to make this work.
See http://book.cakephp.org/2.0/en/core-libraries/behaviors/containable.html#containing-deeper-associations for a complete description.
Also why do you return the data in the controller index? Are you using requestAction for this? And why don't you use pagination? Do you really want to display hundreds of comments on one page?
See http://book.cakephp.org/2.0/en/core-libraries/components/pagination.html
I got problem when save belongto
class Script extends AppModel {
var $name = 'Script';
var $belongsTo = array(
'ScriptCatagories' => array(
'className' => 'ScriptCatagories',
'foreignKey' => 'script_catagories_id',
function add_script() {
pr($this->data);
if (!empty($this->data)) {
$this->Script->create();
$this->data['Script']['script_catagories_id'] = $this->Script->scriptCategory->id;
$this->data['Script']['user_id'] = $this->Auth->user('id');
if ($this->Script->save($this->data)) {
$this->Session->setFlash(__('The script has been saved', true));
$this->redirect(array('action' => 'script_index'));
} else {
$this->Session->setFlash(__('The script could not be saved. Please, try again.', true));
}
}
pr($scriptCatagories = $this->Script->ScriptCatagories->find('list'));
$this->set(compact('scriptCatagories'));
}
when click save
Array
(
[Script] => Array
(
[name] => fdfvvds
[description] => dfvdfvdfvdf
[tags] =>
)
)
Array
(
[0] => performance
[1] => cleanup
)
question in
$this->data['Script']['script_catagories_id'] = $this->Script->scriptCategory->id;
I need to save categoryid to script table but I don't know to get it
thank you
var $belongsTo = array(
'ScriptCatagories' => array(
'className' => 'ScriptCatagories',
'foreignKey' => 'script_catagories_id',
first, it doesn't have close parentheses. And it should be singular ScriptCategory, also the foreign key script_category_id (just to follow the convention). And you misspelled category (you have $this->Script->scriptCategory->id; later in the code)