Cakephp relation modes - cakephp

public $belongsTo = array(
'Hospital' => array(
'className' => 'Hospital',
'foreignKey' => 'hospital_id',
'conditions' => '',
'fields' => '',
'order' => ''
)
);
public $hasMany = array(
'Floor' => array(
'className' => 'Floor',
'foreignKey' => 'hospital_id',
'dependent' => false,
'conditions' => '',
'fields' => '',
'order' => '',
'limit' => '',
'offset' => '',
'exclusive' => '',
'finderQuery' => '',
'counterQuery' => ''
)
);
i have two tables hospitals and floors, i have retrieve data from hospital table and show in floor views in add floor.

You have already set up the relationship, so now you just need to create a controller action and a view.
Assuming your tables are in place, the easiest way to do this would simply be to run cake bake all on the Hospital model and Cake will generate the views for you. Cake is intelligent enough to generate a view that will show you a list of associated floors if that is what you want (it was unclear from your post).

You can retrieve the data from database like this...
mysql_select_db("users"); //your database name
$sql = mysql_query("SELECT * FROM langs"); //table name
$limit = 4;
$count = 3;
echo "<table border='1'>";
while($row = mysql_fetch_array($sql)){
$name=$row['name'];
$email=$row['email'];
$contact=$row['contact'];
if($count < $limit){
echo "<tr>";
}
............. //you can put in table and in any other field
?>

Related

Cakephp pagination using contain produces "not associated" warning

I've got the following models:
Run->hasMany ActualResult
ActualResult belongs to Status
When I view an ActualResult, Cake gets the corresponding Status without straight out of the box.
When I view a Run, I want to paginate the ActualResults. I have managed to get this to almost work with the following code in RunsController::view():
public function view($id = null) {
if (!$this->Run->exists($id)) {
throw new NotFoundException(__('Invalid run'));
}
$this->Run->contain ( 'Pack', 'User', 'Status');
$options = array('conditions' => array('Run.' . $this->Run->primaryKey => $id));
$run = $this->Run->find('first', $options);
$this->set('run', $run);
// Paginate the ActualResults
$this->paginate = array(
'contain' => array('Status'),
'order' => 'ActualResult.format',
'limit'=>5 ,
'conditions' => array('ActualResult.run_id' => $id)
);
$actualResults = $this->Paginator->paginate('ActualResult');
$this->set('actualResults',$actualResults);
}
The problem is that I get a warning:
Warning (512): Model "ActualResult" is not associated with model "Status" [CORE\Cake\Model\Behavior\ContainableBehavior.php, line 343
Something v. similar works for me in another model association, and as mentioned view() in ActualResultController works fine, so I am stumped.
Can anyone help?
Here are the model assocations:
In Run.php:
public $hasMany = array(
'ActualResult' => array(
'className' => 'actual_result',
'foreignKey' => 'run_id',
'dependent' => true,
'finderQuery' => 'SELECT ActualResult.*, Txn.name, Status.name FROM actual_results AS ActualResult, txns as Txn, codes AS Status WHERE ActualResult.run_id = {$__cakeID__$} and Txn.id = ActualResult.txn_id and (Status.code = ActualResult.status and Status.code_type = "ARS");'
)
);
In ActualResult.php
public $belongsTo = array(
'Run' => array(
'className' => 'Run',
'foreignKey' => 'run_id',
'conditions' => '',
'fields' => '',
'order' => ''
),
'Status' => array(
'class`enter code here`Name' => 'Code',
'foreignKey' => 'status',
'conditions' => 'code_type = "ARS"',
'fields' => '',
'order' => ''
)
);

Joins tables in Cakephp

i have a two tables namely; histories and users. i need to display data like:
id | Username | Lastest created Post | First created Post
the data of id and username is from users table and the last created and first created post data is from histories. i need to view all the users, their lastest created post and their first created post. please help me to make controller and view thanks
Try below.
<?php
$users = $this->User->find('all',array
(
'conditions' => array
(
//conditions goes here
),
'fields' => array
(
'User.id',
'User.username',
'History.Lastest created Post',
'History.First created Post'
)
));
?>
Assume that relation between 'User' and 'History' table is One-to-One and there's a 'user_id' column in History table, you may need to specify relation between them in History model, for example:
var $hasOne = array(
'User' => array(
'className' => 'User',
'foreignKey' => 'user_id',
'conditions' => '',
'fields' => '',
'order' => ''
)
);
Then, you need to perform joins to do this. For example, somewhere in your User model, try something like this:
class User extends AppModel {
....
function getAllUsersHistory{
$allHistories = $this->find('all', array(
'joins' => array(
'table' => 'history',
'alias' => 'HistoryJoin'
'type' => 'INNER',
'conditions' => array(
// your conditions, for example: 'History.user_id' => 'User.id'
)
),
'fields' => array(
'User.id',
'User.username',
'History.lastest_created_post',
'History.first_created_post'
)
));
return $allHistories;
}
.....
}

cakePHP saving entries to join table of existing records

first a short description. I have to models: accounts and users and a join table of it accounts_users. the models have a habtm associasions on each model:
User Model:
'Account' => array(
'className' => 'Account',
'joinTable' => 'accounts_users',
'foreignKey' => 'user_id',
'associationForeignKey' => 'account_id',
'unique' => true,
'conditions' => '',
'fields' => '',
'order' => '',
'limit' => '',
'offset' => '',
'finderQuery' => '',
'deleteQuery' => '',
'insertQuery' => ''
)
Account Model:
'User' => array(
'className' => 'User',
'joinTable' => 'accounts_users',
'foreignKey' => 'account_id',
'associationForeignKey' => 'user_id',
'unique' => true,
'conditions' => '',
'fields' => '',
'order' => '',
'limit' => '',
'offset' => '',
'finderQuery' => '',
'deleteQuery' => '',
'insertQuery' => ''
)
Now im trying to save manually relations between this two just to the join table acccounts_users from allready existing entries, here my code
$account = base64_decode($this->params['pass']['0']);
$token = $this->params['pass']['1'];
if($user = $this->User->findByToken($token))
{
// ZUr test zwecken
# $this->User->query(" INSERT INTO accounts_users (account_id ,user_id) VALUES (222, 223); ");
$aId = $this->Account->findById($account);
$this->data['User'][0]['user_id'] = $user['User']['id'];
$this->data['Account'][0]['account_id'] = $aId['Account']['id'];
$this->User->bindModel(array(
'hasMany' => array('AccountsUser')
));
$this->User->saveAll($this->data, array('validate' => false));
print_r('gefunden'); die;
$this->Redirect->flashSuccess('Account Invitation successfull. Log In!', array('controller' => 'users', 'action' => 'login'));
}
else
{
print_r('nicht gefunden'); die;
// user nicht gefunden zum login umleiten
$this->Redirect->flashWarning('Account Invitation error. Please try again!', array('controller' => 'users', 'action' => 'login'));
}
the results are a new entry on the accounts_users table but the user_id is 0. I don't understand why is missing the user id because its passed corectly. even if i pass in the data array some ids manually its writting just the account_id without the user id.
UPDATE
I played a little bit with the models and saved the data to the accounts_users thru the account model see the updated code:
$this->data['User']['id'] = $user['User']['id'];
$this->data['Account']['id'] = 33; #$aId['Account']['id'];
$this->Account->AccountsUser->create();
$this->Account->saveAll($this->data, array('validate' => false));
so now the script inserts both ids, BUT, if there is an entry form another user with the same account id the the user gets overwritten. anything else works. Any idears of how to create a new entry with an axisting account id for new user?
This are the mysql queries i get:
UPDATE accounts SET id = 33 WHERE accounts.id = 33
SELECT AccountsUser.user_id FROM accounts_users AS AccountsUser WHERE AccountsUser.account_id = 33
DELETE AccountsUser FROM accounts_users AS AccountsUser WHERE AccountsUser.account_id = 33 AND
INSERT INTO accounts_users (account_id,user_id) VALUES (33,'32')
Any idears why? Thanks in advance
CakePHP 1.x treats HABTM join tables quite 'dumb'; it will remove all existing records and insert new records to replace them. This is a major PITA if your join-table also contains additional data. (It's possible to prevent this from happening by adding some code in your beforeSave() callbacks)
CakePHP 2.1 has an option keepExisting for HABTM relations. This option prevents CakePHP from deleting the records in the JOIN table. If this is a new project I would really advise to use CakePHP 2.x as a lot has improved since CakePHP 1.x.
http://book.cakephp.org/2.0/en/models/associations-linking-models-together.html#hasmany-through-the-join-model
Some hints on saving data in the join table can be found here;
http://book.cakephp.org/2.0/en/models/saving-your-data.html#saving-hasmany-through-data
For CakePHP 1.3 (look below 'when HABTM becomes complicated)
http://book.cakephp.org/1.3/en/The-Manual/Developing-with-CakePHP/Models.html#saving-related-model-data-habtm

cakephp HABTM database upload cant find issue

I am new to cakePHP and fairly new to PHP as well, I have gone through some Youtube videos to help me make a basic site set up with CRUD pages for everything. I am now trying to set up the user signup page to add a bunch of stuff to a HABTM table but cant figure out what is going wrong.
$this->User->create();
if ($this->User->save($this->data)) {
$lvl = $this->data['User']['level'];
$charids = $this->Kanji->find('list',array('conditions'=>array('grade' <= $lvl,'grade' >= 0)));
foreach ($charids as $charid){
$characterList = array('kanji_id'=>$charid,'user_id'=>$this->User->id, 'level'=>2);
$this->kanjisUsers->save($characterList);
A bit of clarification, The site is for a school project, I want it to help with learning Japanese and the idea is that you can put a string of Japanese text and it will simplify it to your level so when you sign up you tell it what your level of Japanese is (an int between 1 and 9) then it will go through the character list (kanjis table) and find all with a number equal to or less than your level (called 'grade' in the kanjis table) then I want it to add all these to the kanjis_users table with the int 2 to indicate it is known (then I will do it again with one level up characters and save them with int 1 for 'learning')
I had help with the code and am not sure how it all works, I have been changing lots of things and cant figure out what is wrong, any suggestions?
note: I also saw that the model was called kanjis_user.php and KanjisUser, I read the model should not be plural but when I tried to change it everything crashed, could this be a part of the problem?
I have also tried changing => with -> and vice versa and also created $characterList to remove it from the save function, don't know if these affected anything as it never worked...
Edit in response to comment by api55:
Here is the model relation For kanjis_users:
class KanjisUser extends AppModel {
var $name = 'KanjisUser';
//Validation stuff here
var $belongsTo = array(
'Kanji' => array(
'className' => 'Kanji',
'foreignKey' => 'kanji_id',
'conditions' => '',
'fields' => '',
'order' => ''
),
'User' => array(
'className' => 'User',
'foreignKey' => 'user_id',
'conditions' => '',
'fields' => '',
'order' => ''
)
);
Here is the kanji mode:
var $hasAndBelongsToMany = array(
'User' => array(
'className' => 'User',
'joinTable' => 'kanjis_users',
'foreignKey' => 'kanji_id',
'associationForeignKey' => 'user_id',
'unique' => true,
'conditions' => '',
'fields' => '',
'order' => '',
'limit' => '',
'offset' => '',
'finderQuery' => '',
'deleteQuery' => '',
'insertQuery' => ''
)
);
Here is the user model:
var $hasAndBelongsToMany = array(
'Kanji' => array(
'className' => 'Kanji',
'joinTable' => 'kanjis_users',
'foreignKey' => 'user_id',
'associationForeignKey' => 'kanji_id',
'unique' => true,
'conditions' => '',
'fields' => '',
'order' => '',
'limit' => '',
'offset' => '',
'finderQuery' => '',
'deleteQuery' => '',
'insertQuery' => ''
),
This is just the standard generated model (minus validation).
For clarification on the error, there is no error, it just doesn't work, It saves the user, but dose not add anything to the kanjis_users table. Here is the whole register controller as it is now:
function register() {
if (!empty($this->data)) {
$this->User->create();
if ($this->User->save($this->data)) {
$lvl = $this->data['User']['level'];
//$test = $this->Kanji->find ('list',array('Kanji.grade <='<=$lvl, 'AND'=>array('Kanji.grade >=' >= 1)));
$charids = $this->Kanji->find('list',array('conditions'=>array('grade <=' => $lvl,'grade >=' >= 1)));
//print_r($charids);
//exit();
//$this->kanjisUsers->save(array('kanji_id'=>$charids,'user_id'=>$this->User->id));
//$this->kanjisUsers->saveALL(array('kanji_id'=>$charids,'user_id'=>$this->User->id));
foreach ($charids as $charid){
//echo("<p>Charid: ".$charid." is: </p>");
//var_dump($charid);
$this->kanjisUsers->save(array('kanji_id'=>$charid,'user_id'=>$this->User->id),'level'=> 2);
}
//exit();
$this->Session->setFlash(__('The user has been saved', true));
$this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The user could not be saved. Please, try again.', true));
}
}
}
Both seem to generate a similar array, but however I change the code sometimes it will crash, sometimes it will save the user, but it will never do anything to the kanjis_users table.
What I want:(simplified for clarity:
User table has: name, username, pw, userID etc...
kanjis table has: a Chinese character per row with ID, English, grade(int from 0 to 9) etc...
kanjis_users has: ID, user_id, kanji_id, created(date), modified(date), level(int).
I want a user to put a level when they sign up and then when the user gets created it will populate the kanjis_users table with all the rows in the Kanji table that have a 'grade' between 1 and the level the user put in the sign up form (called 'level').
So what I am trying to do above is after the user is saved (this user create() at the top), I then test if the save was a success and then get the level the user put in the form, and try to get all the characters from the rows from the kanjis table where the level is equal to or less than that (note I don't want to get ones with 0 as they are the hardest ones...) and add them all to the kanjis_users table. (this is only for sign up, when using the system the user can add and remove characters as they wish)
I noticed with the print_r that it was getting all 12000~ rows from the kanjis table, so I think the filter was not working...
I hope this makes sense, please let me know if I need to put any further info.
Create an input box in the register view:
$this->Form->input('Kanji', array('type' => 'hidden'));
Then try this:
function register() {
if (!empty($this->data)) {
$this->User->create();
$lvl = $this->data['User']['level'];
$charids = $this->Kanji->find('list',array('conditions'=>array('grade <=' => $lvl,'grade >=' => 1)));
$i = 0;
foreach ($charids as $charid){
$this->data['Kanji']['Kanji'][$i] = $charid;
$i++;
}
if ($this->User->save($this->data)) {
$this->Session->setFlash(__('The user has been saved', true));
$this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The user could not be saved. Please, try again.', true));
}
}
}
How it works
You save current level to $lvl ($this->data['User']['level'];)
You find all Kanjis maching your criteria ($charids = $this->Kanji->find('list',array('conditions'=>array('grade <=' => $lvl,'grade >=' => 1)));)
You define a new variable equal 0 ($i = 0;)
You make a loop going through your data array, storing every Kanjis you found and assigning it to $this->data['Kanji']['Kanji'] as it would be default data if you have selected it in a form.
You save the data as it has been filled by a form.
Ok, I see wrong 2 things :D
1) You get 12000+ rows from the find beacause your find condition is wrong :S and the one commented that i gave you has typos
the find MUST BE like this:
$test = $this->Kanji->find ('list',array(
'conditions'=> array(
'Kanji.grade <=' => $lvl,
'AND' => array(
'Kanji.grade >=' => 1)
)
)
);
2) the data in your save is wrong:
The cookbook explains that the data passed needs to be like this :
Array
(
[ModelName] => Array
(
[fieldname1] => 'value'
[fieldname2] => 'value'
)
)
So your save part should look something like this:
$this->KanjiUser->create();
$data = array(
'KanjiUser' => array(
'KanjiUser.kanji_id'=>$charid,
'KanjiUser.user_id'=>$this->User->id,
'KanjiUser.level'=>2
)
);
if ($this->KanjiUser->save($data))
echo 'Done ;)';
else
echo 'error';
all this inside the foreach or you can do the saveAll approach
$data = array('KanjiUsers'=> array());
foreach ($charids as $charid){
$data ['KanjiUsers'][] = array(
'KanjiUser' => array(
'KanjiUser.kanji_id'=>$charid,
'KanjiUser.user_id'=>$this->User->id,
'KanjiUser.level'=>2
)
);
}
$this->KanjiUser->create();
if ($this->KanjiUser->saveAll($data['KanjiUser'))
echo 'Done ;)';
else
echo 'error';

CakePhp: On the fly associations using a re-named Model field?

I'm trying to use on the fly associations to trim down the data I retrieve, but the model I'm using is associated to other models with a re-named field because I have 2 of the same models associated with it.
So, here's the model, say 'test', that has two 'user' fields, both related to the User model.
In the model:
var $belongsTo = array(
'User' => array(
'className' => 'User',
'foreignKey' => 'user_id'
),
'User_Watched' => array(
'className' => 'User',
'foreignKey' => 'user_id_watched'
)
);
When I retrieve data related to 'test', I want to only retrieve particular data linked to the 'User' and 'User_Watched' fields without any other nested information.
But when I do:
$this->User->unbindModel(array('hasMany' => array('something1', 'something2')), false);
then something1 and something2 data does not show up for the 'User' field of model 'test', but is still retrieved for the 'User_watched' field.
Can I not retrieve unwanted data for the 'User_watched' field?
Hope this makes sense... :)
KcYxA,
Containable behavior might help a lot in this case, as benjamin mentioned, your "find" queries would look like:
$this->User->find('first', array(
'conditions' => array('User.id' => $id),
'contain' => array('UserWatched')
));
In this case, you won't have to use unbindModel method. In this example, you'll get User and UserWatched data.
If you need only User data from "find", then tell Cake to "$this->User->contain();" so it won't go further then User model.
to use on the fly associations to trim
down the data I retrieve
Good idea.
'foreignKey' => 'user_id_watched'
should possibly be:
'foreignKey' => 'user_watched_id'.
Edit 1: At least this would make sense according to my current understanding. If user_id is a correct foreign key(FK), which cakephp uses to unbind the relations, but user_id_watched isn't, than your described behavior is explained.
Edit 2: The Containable behavior gives you another tool for controlling associated models.
Change $primaryKey in fly, run controller
Sample:
// Models
//....
class PreProductoDescripcion extends AppModel {
/**
* Primary key field
*
* #var string
*/
public $primaryKey = 'id_producto_descripcion';
//....
//....
}
class SenasaPedidosDetalles extends AppModel {
/**
* Display field
*
* #var string
*/
public $displayField = 'cod_tango';
public $belongsTo = array(
'SenasaPedidos' => array(
'className' => 'SenasaPedidos',
'foreignKey' => 'senasa_pedidos_id',
'conditions' => '',
'fields' => '',
'order' => ''
),
'PreProductoDescripcion' => array(
'className' => 'PreProductoDescripcion',
'foreignKey' => 'cod_tango',
//'conditions' => array('SenasaPedidosDetalles.cod_tango' => 'PreProductoDescripcion.codigo'),
'fields' => '',
'order' => ''
)
);
//....
#
// Controller Fly
//...
$this->SenasaPedidos->Behaviors->load('Containable');
$this->SenasaPedidos->SenasaPedidosDetalles->PreProductoDescripcion->primaryKey = 'codigo';
$datos = $this->SenasaPedidos->find(
'first', array(
'fields' => array( 'SenasaPedidos.*' ),
'conditions' => array( 'SenasaPedidos.id' => $id ),
'contain' => array(
'Usuarios' => array(
'fields' => array( 'Usuarios.apellido_nombre' )
),
'Clientes' => array(
'fields' => array( 'Clientes.razon_social' )
),
'Provincias' => array(
'fields' => array( 'Provincias.nombre' )
),
'Transportes' => array(
'fields' => array( 'Transportes.razon_social' )
),
'SenasaPedidosDetalles' => array(
'fields' => array( 'SenasaPedidosDetalles.*' ),
'PreProductoDescripcion' => array(
'fields' => array(
'PreProductoDescripcion.id_producto_descripcion',
'PreProductoDescripcion.descripcion'
)
)
),
)
));
//...

Resources