CakePHP trouble linking data from 2 tables in models - php

I am having trouble with linking data like first name from the table Users in the view of chats using cakePHP. Below is my code and whatever I do, the script does not select the user_id from the chats database table to display the first name. I must be overseeing something, but the loop I'm thinking in is giving me some headaches. Can someone please get me out of this loop?
User.php
<?php
class User extends AppModel {
public $hasMany = array(
'Ondutylog',
'Chat'
);
}
?>
Chat.php
<?php
class Chat extends AppModel {
public $belongsTo = array(
'User'
);
}
?>
ChatsController.php
<?php
class ChatsController extends AppController {
var $uses = array('User', 'Chat');
public function view() {
$chats = $this->Chat->find('all', array(
'order' => array('id' => 'ASC'),
'recursive' => -1
));
$this->set('chats', $chats);
$id = $chats['Chat']['user_id'];
$userdetails = $this->Chat->User->find('first', array(
'conditions' => array(
'id' => $id
),
recursive' => -1
));
return $userdetails;
}
}
?>
view.ctp
<?php
foreach($chats as $chat) :
echo "<tr>";
echo "<td>".$userdetails['User']['firstname']."</td>";
echo "<td>".$chat['Chat']['user_id']."</td>";
echo "<td>".$chat['Chat']['text']."</td>";
echo "<td>".$chat['Chat']['created']."</td>";
echo "</tr>";
endforeach
?>
The array I get returned in $chats
[Chat] => Array
(
[id] => 1
[user_id] => 11
[text] => hello
[created] => 2014-05-21 19:56:16
[modified] => 2014-05-21 19:56:16
)

Change
return $userdetails;
to
$this->set(compact('userDetails'));
You are supposed to set the view var not return the info.
Though why are you making a separate query for it instead of just using 'recursive' => 0 which would get the associated user record through table join and you can just use $chat['User']['firstname'] in view.
Also get rid of var $uses = array('User', 'Chat');. It's not needed. $this->Chat is already available and the User model is accessed through association as $this->Chat->User as you have already done.

You need charge the model in your controller
class ChatsController extends AppController {
public function view() {
$this->loadModel('User');
$this->loadModel('Chat');
$chats = $this->Chat->find('all', array(
'order' => array('id' => 'ASC'),
'recursive' => -1
));
$this->set('chats', $chats);
$id = $chats['Chat']['user_id'];
$userdetails = $this->Chat->User->find('first', array(
'conditions' => array(
'id' => $id
),
recursive => -1
));
$this->set(compact('userDetails'));
}
}

I found the solution and it's closer than I thought of myself. Because the Models User and Chat were already joined I just had to use a couple of lines in the Controller. So I modified it like this:
public function view() {
$chats = $this->Chat->find('all');
$this->set('chats', $chats);
}
And nothing more...

Related

cakephp conditions based on HABTM relation

User Model has relation:
public $hasMany = array(
'MyRecipe' => array(
'className' => 'Recipe',
)
);
I want to select all users who have recipes with ID: 1,2
How I can use that conditions in select:
$this->User->find('all', array(
'conditions' => array(
'Recipe.Id' => [1,2]
)
));
But in this example I will get also Users without recipes, how to prevent that ?
please give this relation in User model
class User extends AppModel
{
var $name = 'User';
var $belongsTo = array("Recipe");
}
and in user controller your query as
$list = $this->User->find('all',array("conditions"=>array("recipe_id IN"=> [1,2] )));
its gives output which you want..

CakePHP recursive not working with conditions

I have a problem with querying associated data from a Model in CakePHP. I wrote an example to show the behavior:
TestController.php:
class TestController extends AppController
{
public $uses = array(
'User',
'Upload',
'Detail'
);
public function test(){
$result = $this->Upload->find('all', array(
'recursive' => 2,
'conditions' => array('Detail.id' => 1)
));
print_r($result);
}
}
Upload.php:
class Upload extends AppModel {
public $belongsTo = array(
'User' => array(
'className' => 'User',
'foreignKey' => 'user_id'
)
);
}
Detail.php:
class Detail extends AppModel {
public $belongsTo = array(
'User' => array(
'className' => 'User',
'foreignKey' => 'user_id'
)
);
}
User.php:
class User extends AppModel {
public $hasOne = 'Detail';
public $hasMany = array(
'Upload' => array(
'className' => 'Upload',
'foreignKey' => 'user_id',
)
);
}
When I remove the condition I get back an array with Details included. But with the condition I get the following error:
Error: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'Detail.id' in 'where clause'
Looking at the SQL Queries it seems like he is not joining the tables correctly when I add the condition. Without the condition he is joining all three tables.
Is this a bug in CakePHP or am I doing anything wrong?
No, it is not a bug with CakePHP. It's simply the way it's designed, using conditions during a find on associated models will often create an invalid query. You should be using containable behavior or manually joining to use conditions on associated models.
Also, I suspect that you will not get the results you are looking for doing this way anyways. CakePHP by default uses left joins. Therefore, your results will not be limited by those associated with the desired Detail ID, but rather, it will get all uploads, all users associated with those uploads, and then only those details associated with those users that have the correct ID. The simplest way then to get what you're probably looking for is to do the query from the opposite direction:
$result = $this->Detail->find('all', array(
'recursive' => 2,
'conditions' => array('Detail.id' => 1)
));
EDIT: If you do want to do left joins, then make your query this way:
$result = $this->Upload->find('all', array(
'contain' => array('User' => array('Detail' => array('conditions' => array('Detail.id' => 1))),
));

Multiple levels of "has many" relationship

I want to achieve a structure where e.g. an Organisation has many Departments, and where Departments has many Persons.
I've set up my model structure like this:
Organisations
<?php
class Organisation extends AppModel {
public $hasMany = array(
'Department' => array(
'className' => 'Department',
'foreignKey' => 'organisations_id'
)
);
}
Departments
<?php
class Department extends AppModel {
public $hasMany = array(
'Person' => array(
'className' => 'Person',
'foreignKey' => 'departments_id'
)
);
}
Persons
<?php
class Person extends AppModel {
}
Then I have a controller like this:
<?php
class OrganisationsController extends AppController {
public $helpers = array('Html', 'Form', 'Session');
public $components = array('Session');
public function index() {
$this->set('organisations', $this->Organisation->find('all'));
}
}
When I print out $organisations I get an array like this:
Array
(
[0] => Array
(
[Organisation] => Array
(
[id] => 1
[created] => 2013-01-03 16:02:47
)
[Department] => Array
(
[0] => Array
(
[id] => 1
[created] => 2013-01-03 16:02:47
[organisations_id] => 1
)
)
)
)
I'm new to both PHP and CakePHP, but wouldn't you expect the Person array to be included in the Organisation array? And if not, is there another way to achieve a structure like the one described above (Organisation->Department->Person)?
Any hints on how to go about this is highly appreciated! :)
You are probably looking for recursive
Or you could make use of the containable behaviour
But please have a look at the result. When using recursive you can get a lot of data you don't want! So please be careful and select the fields you actually need!
Recursive
You would get something like:
<?php
class OrganisationsController extends AppController {
public $helpers = array('Html', 'Form', 'Session');
public $components = array('Session');
public function index() {
$this->Organisation->recursive = 2; # or -1, 0, 1, 2, 3
$this->set('organisations', $this->Organisation->find('all'));
}
}
You could also declare this in the find itself like so:
$this->set('organisations', $this->Organisation->find('all' array(
'recursive' => 2 # or -1, 0, 1, 2, 3
)
));
Containable
class Organisation extends AppModel {
public $hasMany = array(
'Department' => array(
'className' => 'Department',
'foreignKey' => 'organisations_id'
)
);
$actsAs = array('Containable');
}
Now in your controller you can do something like:
$this->set('organisations', $this->Organisation->find('all', array(
'contain' => array('User')
)
));
But as always, there are many roads leading to Rome. So please read the books very carefully!
http://book.cakephp.org/2.0/en/index.html
http://book.cakephp.org/2.0/en/models/model-attributes.htm
http://book.cakephp.org/2.0/en/core-libraries/behaviors/containable.html
http://book.cakephp.org/2.0/en/models/retrieving-your-data.html
Recursive function will do it for you.
Just in OrganisationsController index function , try doing like below.
$this->Organisation->recursive = 2;
$this->set('organisations', $this->Organisation->find('all'));
Note: Recursive may affect your performance , you can use unbind method to get rid of it by just fetching the data you want.

cakephp HABTM save null field

I have a site develop in cakephp 2.0.
I have a relation HABTM to the same model like this:
class Product extends AppModel {
public $name = 'Product';
public $useTable = 'products';
public $belongsTo = 'User';
public $actsAs = array('Containable');
public $hasAndBelongsToMany = array(
'Product' => array(
'className' => 'Product',
'joinTable' => 'ingredients_products',
'foreignKey' => 'product_id',
'associationForeignKey' => 'ingredient_id',
'unique' => false
)
);
}
I want to save a record into my view with a simple form like this:
echo $this->Form->create('IngredientProduct', array ('class' => 'form', 'type' => 'file'));
foreach ($product as $prod) {
echo '<div>'.$prod['ProductAlias']['alias'].'</div>';
echo $this->Form->input('IngredientProduct.product_id', array ('type'=>'text', 'value'=> $prod['ProductAlias']['id'], 'label'=> false, 'id' => 'id'));
}
$select = '<select name="data[IngredientProduct][ingredient_id]" id="[IngredientProductIngredientId">';
foreach ($other_product as $prod2) {
$select .= '<option value="'.$prod2['ProductAlias']['id'].'">'.$prod2['ProductAlias']['alias'].'</option>';
}
$select .= '</select><br>';
echo($select);
echo $this->Form->submit('Collega', array('id'=>'link_product'));
echo $this->Form->end();
Into my controller I save in this mode:
if ($this->Product->saveAll($this->request->data)){
$this->Session->write('flash_element','success');
$this->Session->setFlash ('Prodotto collegato con successo.');
//$this->redirect(array('action'=>'edit',$alias));
}
else{
$this->Session->write('flash_element','error');
$this->Session->setFlash('Errore di salvataggio activity');
}
When I'm going to see into the database I see that ingredient:id is setting well but product_id is 0.
I have debugged my request->data and this is the array:
array(
'IngredientProduct' => array(
'product_id' => '1',
'ingredient_id' => '2'
)
)
I have print the sql query created by cakephp:
INSERT INTO `db`.`ingredients_products` (`product_id`, `ingredient_id`, `modified`, `created`) VALUES ('', 2, '2012-10-09 23:19:22', '2012-10-09 23:19:22')
Why product_id is null instead of 1?
Can someone help me?
Thanks
I think this line is wrong:
$this->Product->saveAll($this->request->data);
Try:
$this->IngredientProduct->saveAll($this->request->data);
as your form seems to ask data for a relationship, not a new product.

cakePHP bind hasmany through relationship

Ok this is kind of hard to explain but I'll try my best.
I have 3 tables
companies products product_availabilities
--------- -------- ----------------------
id id id
name name company_id
product_id
buys (tinyint)
sells (tinyint)
And their models
class Company extends AppModel
{
public $name = 'Company';
public $hasMany = array(
'ProductAvailability'
);
class Product extends AppModel
{
public $name = 'Product';
public $hasMany = array(
'ProductAvailability'
);
class ProductAvailability extends AppModel
{
public $name = 'ProductAvailability';
public $belongsTo = array(
'Company',
'Product'
);
}
What I want to do is when I create a company, I want to be able to select products that the company buys or sells. I've seen an example of a hasMany through relationship in the book (http://book.cakephp.org/1.3/view/1650/hasMany-through-The-Join-Model) but they are creating the form from the "join table" controller. Is it possible to bind the productAvailability model to my company model to be able to select the products while creating the company?
Edit : Here is how I've done it. I know it is not optimal as there is a lot of looping involved but it works.
Company controller :
$products = $this->Company->ProductAvailability->Product->find('list', array('fields' => array('Product.id', 'Product.label')));
$this->set('products', $products);
if($this->request->is('post')){
if($this->Company->save($this->request->data)){
foreach($products as $product)
{
$tmpArray = array(
'company_id' => $this->Company->id,
'product_id' => $product['Product']['id']
);
foreach($this->request->data('BuyProducts.product_id') as $buyProduct)
{
if($buyProduct == $product['Product']['id'])
$tmpArray['buys'] = 1;
}
foreach($this->request->data('SellProducts.product_id') as $sellProduct)
{
if($sellProduct == $product['Product']['id'])
$tmpArray['sells'] = 1;
}
if(count($tmpArray) > 2)
{
$this->Company->ProductAvailability->create();
$this->Company->ProductAvailability->set($tmpArray);
$this->Company->ProductAvailability->save();
}
}
$this->Session->setFlash('Yay', 'success');
$this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash('Nay', 'error');
}
}
Company add form :
<?php echo $this->Form->create('Company'); ?>
<?php echo $this->Form->input('name', array( 'div' => 'full-form')); ?>
<?php echo $this->Form->input('BuyProducts.product_id', array('multiple' => 'checkbox', 'options' => $products, 'div' => 'full-form', 'label' => false)); ?>
<?php echo $this->Form->input('SellProducts.product_id', array('multiple' => 'checkbox', 'options' => $products, 'div' => 'full-form', 'label' => false)); ?>
<?php echo $this->Form->end(array('label' => __('Save'), 'div' => 'center', 'class' => 'bouton-vert')); ?>
You have two options. Either let cakePHP do some magic with the hasAndBelongsToMany relationship or doing it manually which is necessary if you add attributes to the join table
1. CakePHP HABTM
Using the capabilities of CakePHP and making a straight forward solution I would make these changes:
Model
If one company has more than one product, and the products belong to many companies. It is a hasAndBelongsToMany relationship between Company<->Product
// company.php
...
var $hasAndBelongsToMany = array(
'Product' => array(
'className' => 'Product',
'joinTable' => 'companies_products',
'foreignKey' => 'company_id',
'associationForeignKey' => 'product_id',
'unique' => true,
)
);
...
// similar in product.php
Add the required table 'companies_products' in the database.
Controller
Then in the add function from the Company Controller there should be something like:
$products = $this->Company->Product->find('list');
$this->set(compact('products'));
View
Finally insert the products in the add.ctp, the select should allow multiple selections and let cakePHP do some magic, like this:
echo $this->Form->input('products', array(
'label' => 'Products to buy (Ctr+multiple choice)'
'type' => 'select',
'multiple' => true,
));
2. Manually
When the HABTM becomes more 'exotic' and includes some attributes like in your case 'buy' or 'sell' you need to do the manual way. This is in the Product Controller setting manually the fields before inserting them in the database. Something like:
foreach($availableProducts as $availableProduct ){
$this->Product->ProductAvailabilities->create();
$this->Product->ProductAvailabilities->set( array(
'company_id' => $this->Product->id,
'product_id' => $availableProduct['Product']['id'],
'buys' => $availableProduct['Product']['buy'],
'sells' => $availableProduct['Product']['sell']
// or however you send it to the controller
));
$this->Product->ProductAvailabilities->save();
}
Let's hope this helps you ...
you are planning a habtm-relationship (m:n) with the possibility to have extra fields in the join table. Even though this can be done with regular habtm I prefer the way you choose and implement the m:n as 1:n:1, which is simply the same and gives you more options when saving your data.
Here is a similar question and answer
As for your question: You can collect the the data from your products table like this:
$this->Company->ProductAvailability->Product->find('all', $params);
Also you might want to have a look at the containable-behaviour which is very useful for this use case:
$params['conditions'] = array(
'Company.id' => $id
);
$params['contain'] => array(
'ProductAvailability' => array(
'conditions' =>array(
'buys' => 1
),
'Product' => array(
'order' => array(
'name' => 'ASC'
)
)
)
);
$this->Company->find('all', $params);

Categories