Join two tables using specified fields in CakePHP - cakephp-2.0

I have two tables called Siteaddress and Jobsheet. In the Jobsheet table there is a field called siteaddress that contains the ID of the site address stored in the Siteaddress table.
The problem I am having is that while I'm doing the join in the controller, CakePHP is joining the Siteaddress table to the Jobsheet table using the id fields in both tables. This causes a problem as there is only one record (so far) in the Siteaddress table, and multiple records in the Jobsheet table.
What I need to do is tell CakePHP to join Jobsheet.siteaddress to Siteaddress.id instead of the way it's working at the moment.
How am I able to do this?
Below is the relationship code from the Jobsheet model file:
public $hasOne = array(
'Company' => array(
'className' => 'Company',
'foreignKey' => 'id',
'conditions' => '',
'fields' => '',
'order' => ''
),
'Siteaddress' => array(
'className' => 'Siteaddress',
'foreignKey' => 'id',
'conditions' => '',
'fields' => '',
'order' => ''
)
);
Cheers!

You've set the foreignKey to id so Cake uses this for making the join. This key can be set to any table field you want in the table you want joined. If I understand you correctly you should set the foreignKey to siteaddress:
'Siteaddress' => array(
'className' => 'Siteaddress',
'foreignKey' => 'siteaddress',
'conditions' => '',
'fields' => '',
'order' => ''
)
See the manual entry for hasOne as well.
EDIT:
In this case $belongsTo might be a better fit as an association.

Related

CakePHP 2.x HABTM join table with extra fields

In a CakePHP 2.3.1 project, I have a typical HABTM relationship between two classes, but I want to add an extra field to the join table. in the Cakephp docs http://book.cakephp.org/2.0/en/models/saving-your-data.html#saving-habtm. It says that's possible but it doesn't say how :
Also note that if you want to add more fields to the join (when it was created or meta information) this is possible with HABTM join tables...
(I don't wanna use the hasmany solution it's not suitable for my case, as I need to have the multiselection possibility in my form).
Yes definitely you can add fields in HABTM Relation ship in CakePHP 2.X
Check out the below sample HABTM Relationship:
var $hasAndBelongsToMany = array(
'Category' => array(
'className' => 'Category',
'joinTable' => 'user_categories',
'foreignKey' => 'user_id',
'associationForeignKey' => 'category_id',
'with' => 'UserCategory',
'unique' => 'true',
'fields' => 'User.name',
'order' => '',
'limit' => '',
'offset' => '',
'finderQuery' => '',
'deleteQuery' => '',
'insertQuery' => ''
)
);
In the above "fields" option u can mention your join fields if any and it will work.

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 - cant pull model association via belongsTo in second recursion

cakephp I try to get a find('all'...) on a model with many associations in cakePHP 1.3, which does have the filter criteria for the query in the second level of the recursion within the schema. Simply, it looks like this and I want to filter for the UserId:
Delivery belongsTo Order, Order belongsTo User.
Here are the assocs:
Order:
var $belongsTo = array(
'User' => array(
'className' => 'User',
'foreignKey' => 'user_id',
'conditions' => '',
'fields' => '',
'order' => ''
),....
Delivery:
var $belongsTo = array(
'Order' => array(
'className' => 'Order',
'foreignKey' => 'order_id',
'conditions' => '',
'fields' => '',
'order' => ''
),...
The resulting error is:
SQL Error: 1054: Unknown column 'User.id' in 'where clause' [CORE/cake/libs/model/datasources/dbo_source.php, line 684]
Here the full query, just for fun:
SELECT Delivery.id, Delivery.order_id, Delivery.delivery_address_id, Delivery.deliver_date, Delivery.created, Delivery.modified, Delivery.deliver_run, Delivery.product_mix_id1, Delivery.product_mix_id2, Delivery.product_mix_id3, Delivery.product_mix_id4, Delivery.assembled, Delivery.shipped, Delivery.rated, Delivery.price, Delivery.product_lines_id, Order.id, Order.user_id, Order.product_lines_id, Order.order_date, Order.deliver_monday, Order.deliver_tuesday, Order.deliver_wednessday, Order.deliver_thursday, Order.deliver_friday, Order.deliver_saturday, Order.delivery_address_id, Order.payment_delay, Order.active, Order.cancle_date, Order.replaced_order_id, Order.created, Order.modified, DeliveryAddress.id, DeliveryAddress.delivery_company, DeliveryAddress.delivery_title, DeliveryAddress.delivery_first_name, DeliveryAddress.delivery_last_name, DeliveryAddress.delivery_street, DeliveryAddress.delivery_house_nr, DeliveryAddress.delivery_postal_code, DeliveryAddress.delivery_town, DeliveryAddress.delivery_country, DeliveryAddress.created, DeliveryAddress.deleted, DeliveryAddress.modified, ProductLine.id, ProductLine.name, ProductLine.description, ProductMix1.id, ProductMix1.name, ProductMix1.description, ProductMix1.image_small_path, ProductMix1.image_normal_path, ProductMix1.product_categories_id, ProductMix1.depricated, ProductMix1.created, ProductMix1.modified, ProductMix2.id, ProductMix2.name, ProductMix2.description, ProductMix2.image_small_path, ProductMix2.image_normal_path, ProductMix2.product_categories_id, ProductMix2.depricated, ProductMix2.created, ProductMix2.modified, ProductMix3.id, ProductMix3.name, ProductMix3.description, ProductMix3.image_small_path, ProductMix3.image_normal_path, ProductMix3.product_categories_id, ProductMix3.depricated, ProductMix3.created, ProductMix3.modified, ProductMix4.id, ProductMix4.name, ProductMix4.description, ProductMix4.image_small_path, ProductMix4.image_normal_path, ProductMix4.product_categories_id, ProductMix4.depricated, ProductMix4.created, ProductMix4.modified FROM deliveries AS Delivery LEFT JOIN orders AS Order ON (Delivery.order_id = Order.id) LEFT JOIN delivery_addresses AS DeliveryAddress ON (Delivery.delivery_address_id = DeliveryAddress.id) LEFT JOIN product_lines AS ProductLine ON (Delivery.product_lines_id = ProductLine.id) LEFT JOIN product_mixes AS ProductMix1 ON (Delivery.product_mix_id1 = ProductMix1.id) LEFT JOIN product_mixes AS ProductMix2 ON (Delivery.product_mix_id2 = ProductMix2.id) LEFT JOIN product_mixes AS ProductMix3 ON (Delivery.product_mix_id3 = ProductMix3.id) LEFT JOIN product_mixes AS ProductMix4 ON (Delivery.product_mix_id4 = ProductMix4.id) WHERE User.id = 1
Does anyone know why cake does not pull the second level, in this case the User model, when even recursive is set to 5?
Many thanks.
EDIT: It just occurred to me that in your case you don't need 2nd level JOIN actually, as you can filter by Order.user_id (instead of User.id)! Do you see my point?
So probably you don't need solution below.
As far as I know, Cake never does 2nd level JOIN itself, so for filtering (conditions) on 2nd level (and deeper) I use joins.
For your example:
$options['joins'] = array(
array(
'table' => 'orders',
'alias' => 'Order',
'type' => 'LEFT',
'conditions' => array(
'Order.id = Delivery.order_id',
)
),
array(
'table' => 'users',
'alias' => 'User',
'type' => 'LEFT',
'conditions' => array(
'User.id = Order.user_id',
'User.some_field' => $someFilteringValue
)
)
);
$result = $this->Delivery->find('all', $options);

Error in association or containment

This is one of those times when I know I'm doing something wrong, but I'm apparently deaf, dumb and blind with respect to seeing it. I'm hoping that another pair of eyes can open my own.
I have a ZipCode model and an Incentive model. There is a glorified join table (glorified because it has its own key) sitting in the middle. The join table has id, incentive_id and zip fields (legacy database). My ZipCode model HABTM Incentive as shown:
public $hasAndBelongsToMany = array(
'Incentive' => array(
'with' => 'ZipCodeIncentive',
'foreignKey' => 'zip',
'associationForeignKey' => 'incentive_id',
),
);
My Incentive model HABTM ZipCode as follows:
public $hasAndBelongsToMany = array(
'ZipCode' => array(
'with' => 'ZipCodeIncentive',
'foreignKey' => 'incentive_id',
'associationForeignKey' => 'zip',
),
I have a method, ZipCode::incentives( $zip ) that wants to pull all of the incentives relevant to the specified zip code:
$incentives = $this->Incentive->find(
'all',
array(
'contain' => array( 'ZipCode' ),
'fields' => array( 'Incentive.id', 'Incentive.name', 'Incentive.it_name', 'Incentive.amount', 'Incentive.state', 'Incentive.entire_state', 'Incentive.excluded', 'Incentive.is_active' ),
'conditions' => array(
'Incentive.excluded' => 0,
'Incentive.is_active' => 1,
'OR' => array(
'Incentive.state' => 'US', # nationwide incentives
array(
# Incentives that apply to the entire state the zip code belongs to
'Incentive.entire_state' => 1,
'Incentive.state' => $state,
),
'ZipCode.zip' => $zip # specific to the building's zip code
)
),
'order' => array( 'Incentive.amount DESC' ),
)
);
What I get for my trouble is the following error:
SQL Error: 1054: Unknown column 'ZipCode.zip' in 'where clause'
The ZipCode model's table isn't getting joined in the SQL, but I haven't grasped why yet. It's worth mentioning that the Incentive model is tied to a MySql view, not a table, via $useTable. I haven't seen anything to suggest that it should be a problem in this scenario, but it's non-standard.
If you see what I'm missing, please call 911 or at least drop an answer.
Rob
Move the condition
'ZipCode.zip' => $zip
To your contain declaration like this
array(
'contain' => array( 'ZipCode'=>
array('conditions'=>
array('ZipCode.zip' => $zip ))),
Then continue with the rest of your statement as usual

Resources