HABTM Cake php find - php

I have tables below with HABTM associations.
user, group , groups_users
group , project, projects_groups
public $hasAndBelongsToMany = array(
'Group' =>
array(
'className' => 'Group',
'joinTable' => 'groups_users',
'foreignKey' => 'user_id',
'associationForeignKey' => 'group_id',
'unique' => 'keepExisting',
'conditions' => '',
'fields' => '',
'order' => '',
'limit' => '',
'offset' => '',
'finderQuery' => ''
)
);
I am trying to get all users, as a list for checkboxes, that are on a project using project id using query below
$users = $this->User->Group->Project->find('list',
array(
'conditions' => array('Project.id' => $this->Session->read('Projectid'))
,'contain' => array(
'User' => array( 'fields' => 'User.id', 'User.email')
)
)
);
But error below
Model "Project" is not associated with model "User"
I have actually tried different ways to get this working but cant seem to get it right, how can i achieve what i want. cheers

I achieved what i wanted with joins , is there a way to do this by using model associations, instead of the manual joins option?
$options['joins'] = array(
array('table' => 'groups_users',
'alias' => 'gu',
'type' => 'LEFT',
'conditions' => array(
'gu.user_id = User.id',
)
),
array('table' => 'projectGroups',
'alias' => 'pg',
'type' => 'LEFT',
'conditions' => array(
'pg.group_id = gu.group_id',
)
)
);
$this->User->recursive = -1;
$options['conditions'] = array(
'pg.project_id = ' => $this->Session->read('Projectid'),
'User.Active = ' => true
);
$users = $this->User->find('list', $options);

Related

CakePHP JOIN not working

I am new in cakephp and I have searched a lot but couldn't get the solution. My query is not returning any error but it doesn't join the zone table with the disposeTemp table.
public function disposePreview(){
$this->loadModel('DisposeTemp');
$joins = array(
array(
'table' => 'zones',
'alias' => 'Zone',
'type' => 'inner',
'conditions' => array('DisposeTemp.zone = Zone.id')
)
);
$options = array(
'conditions' => array('DisposeTemp.is_delete' => 0,'DisposeTemp.status'=>2),
'order' => array('Item.item_category_id' => 'asc'),
'joins' => $joins
);
$getDT = $this->DisposeTemp->find('all', $options);
debug($getDT);
exit;
}
Set foreign key false , as you are not having proper naming convention for foreign key in DisposeTemp table , it was supposed to be zone_id to auto form relationship.
Now in your situation Use.
$joins = array(
array(
'table' => 'zones',
'alias' => 'Zone',
'type' => 'inner',
'foreignKey' => FALSE,
'conditions' => array('DisposeTemp.zone = Zone.id')
)
);

CakePHP HABTM condition

I want to make a condition on my HABTM attributes
I have the following HABTM relations in CakePHP 2.x:
Practise.php
public $hasAndBelongsToMany = array(
'Attribute' => array(
'className' => 'Attribute',
'joinTable' => 'practises_attributes',
'foreignKey' => 'practise_id',
'associationForeignKey' => 'attribute_id',
'unique' => true,
'conditions' => '',
'fields' => '',
'order' => '',
'limit' => '',
'offset' => '',
'finderQuery' => '',
)
);
Attribute.php
public $hasAndBelongsToMany = array(
'Practise' => array(
'className' => 'Practise',
'joinTable' => 'practises_attributes',
'foreignKey' => 'attribute_id',
'associationForeignKey' => 'practise_id',
'unique' => true,
'conditions' => '',
'fields' => '',
'order' => '',
'limit' => '',
'offset' => '',
'finderQuery' => '',
)
);
Now I want to find all including a condition on Attributes in my PractiseController.php
PractiseController.php
$cond['Attribute.id'] = array(1,2,3);
$this->Practise->find('all', array('conditions' => $cond));
Then I get the following error:
Error: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'Attribute.id' in 'where clause'
SQL Query:
SELECT
Practise.id,
Practise.title,
Practise.body,
FROM db.practises AS Practise
WHERE Attribute.id IN (1, 2, 3)
How can I make CakePHP also Join the HABTM table into the find query?
You can use contain for example
$this->Practise->find('all', array('contain' => 'Attribute.id = whatever'));
You can manually join too with:
$options['joins'] = array(
array('table' => 'practises_attributes',
'alias' => 'PractiseAttribute',
'type' => 'INNER',
'conditions' => array(
'Attribute.id = whatever',
)
) );

DISTINCT not working with hasMany cakephp

I want to apply DISTINCT query in cakephp 2+ it's working fine but when I BindModel with that model it's not working ?
Here is my code please check it..
$this->User->bindModel(
array(
'hasMany' => array(
'UserPreference' => array(
'className' => 'UserPreference',
'foreignKey' => 'user_id',
'fields' => 'UserPreference.notification_status',
'conditions' => array('UserPreference.notification_status' => 1),
)
)
)
);
$data = $this->User->find('all', array('conditions' => array('app_id NOT ' => '0', 'User.status' => 1), 'fields' => array('DISTINCT User.app_id')));
pr($data); die;
just because I once happened something like this I fix it changing this:
$this->User->bindModel(
array(
'hasMany' => array(
'UserPreference' => array(
'className' => 'UserPreference',
'foreignKey' => 'user_id',
'fields' => 'UserPreference.notification_status',
'conditions' => array('UserPreference.notification_status = 1'),
)
)
)
);

cakephp find all join

$order = $this->Order->find('all', array(
'recursive' => 2,
'conditions' => array(
'Order.date' => $datefrom,
),
'joins' => array(
array(
'table' => 'purchase',
'alias' => 'Purchase',
'conditions'=> array(
'Purchase.pid = Order.pid',
)
),
array(
'table' => 'sales',
'alias' => 'Sales',
'conditions'=> array(
'Purchase.pid = Sales.pid',
)
),
),
));
Why does the above code doesn't select fields from purchase and sales, but only fields from order are returned. What is the necessary things to be added to make all data is returned. Thanks
Try this, I'm not sure if the 'type' and 'foreignKey' keys are required, but I typically include them when using the 'joins' key. Also I'm assuming the 'pid' is the correct foreign key.
$order = $this->Order->find('all', array(
'recursive' => -1,
'conditions' => array(
'Order.date' => $datefrom,
),
'joins' => array(
array(
'table' => 'purchase',
'alias' => 'Purchase',
'type' => 'INNER',
'foreignKey' => 'pid',
'conditions'=> array(
'Order.pid = Purchase.pid',
)
),
array(
'table' => 'sales',
'alias' => 'Sales',
'type' => 'INNER',
'foreignKey' => 'pid',
'conditions'=> array(
'Sales.pid = Purchase.pid',
)
),
),
));
If you already have relationships set up in the model, change the 'recursive' key to -1.
Just an idea,
'table' => 'purchase',
'alias' => 'Purchase',
isn't a typo, is it? Because I think, the usual name for the table according to cake-conventions would be 'purchases'... But I don't know your tables of course... ;)
First you need to create an association in Order Model file
Model:
public $hasMany = array(
'purchase' => array(
'className' => 'purchase',
'foreignKey' => 'pid',
'dependent' => true,
'counterQuery' => 'true'
),
'sales' => array(
'className' => 'sales',
'foreignKey' => 'pid',
'dependent' => true,
'counterQuery' => 'true'
),
);
Controller:
$order = $this->Order->find('all', array(
'recursive' => 2,
'conditions' => array(
'Order.date' => $datefrom,
)
);
Now you can get Order, Purchase and Sales related records.
Enjoy...
Controller::loadModel('User');
Controller::loadModel('Answer');
Controller::loadModel('Influence');
$users = $this->User->find('all', array('joins' => array(
array(
'table' => 'answers',
'alias' => 'Answer',
'type' => 'inner',
'foreignKey' => false,
'conditions' => array('Answer.user_id = User.id'),
),
array(
'table' => 'influences',
'alias' => 'Influence',
'type' => 'inner',
'foreignKey' => false,
'conditions' => array(
'Influence.user_id=Answer.user_id',
)
)
),'fields' => array(
'Answer.is_correct',
'Answer.answer',
'Answer.date as answered_date',
'Influence.signups',
'Influence.clicks',
'User.first_name',
'User.last_name',
'User.email',
'User.phone',
'User.flybuys' )
));
In order to get fields from other tables You should specify the fields you want.

CakePHP SQL Error

Im trying to do a purge of records in a database though when I made my query and associations it seems to not want to do it correctly. I got the following error and Im confused as to why this is occurring:
SQL Error: 1054: Unknown column 'GuardiansStudents.student_id' in 'where clause'
The query that gets displayed afterwards is the following:
Query: SELECT `User`.`id`, `Guardian`.`id`
FROM `guardians` AS `Guardian`
LEFT JOIN `users` AS `User` ON (`Guardian`.`user_id` = `User`.`id`)
WHERE `GuardiansStudents`.`student_id` IS NULL
AND `User`.`active` = 1 AND `User`.`changeapprovalneeded` = 0
I also have the following associations in the Guardian model, not sure if Im doing this properly, and possibly this is where the error is occurring:
class Guardian extends AppModel {
var $name = 'Guardian';
//The Associations below have been created with all possible keys,
// those that are not needed can be removed
var $belongsTo = array(
'User' => array(
'className' => 'User',
'foreignKey' => 'user_id',
'conditions' => '',
'fields' => '',
'order' => ''
),
);
var $hasAndBelongsToMany = array(
'Student' => array(
'className' => 'Student',
'joinTable' => 'guardians_students',
'foreignKey' => 'guardian_id',
'associationForeignKey' => 'student_id',
'unique' => true,
'conditions' => '',
'fields' => '',
'order' => '',
'limit' => '',
'offset' => '',
'finderQuery' => '',
'deleteQuery' => '',
'insertQuery' => ''
)
);
This is the code to do the purge function:
function manager_purgebygrade() {
ini_set('max_execution_time','120');
$this->layout = "manager";
$this->User->recursive = 0;
$grades = $this->User->Student->Grade->getDropDownList();
$this->set(compact('grades'));
//debug($this->data);
if(!empty($this->data['User']['grade_id']))
{
//$this->User->bindModel(array())
$users = $this->User->find(
'list',
array(
'fields' => array(
'User.id'
),
'conditions' => array(
'Student.grade_id' => $this->data['User']['grade_id']
),
'recursive' => 0
)
);
//debug($users);
$this->User->deleteAll(array('User.id' => $users), true);
$this->User->Guardian->bindModel(
array('hasOne' => array('GuardiansStudents')));
$guardianswithnostudents = $this->Guardian->deleteGuardiansWithNoStudent();
$guardians = $this->User->Guardian->find(
'list',
array(
'fields' => array(
'User.id',
'User.id'
),
'conditions' => array(
'GuardiansStudents.student_id' => null,
'User.active' => 1,
'User.changeapprovalneeded' => 0
),
'recursive' => 1
)
);
$this->User->deleteAll(array('User.id' => $guardians), true);
$this->set(compact('users','guardians','guardianswithnostudents'));
}
}
Hopefully someone can point me in the right direction I would greatly appreciate it :).
Your where clause:
WHERE `GuardiansStudents`.`student_id` IS NULL
is using table GuardiansStudents that appears nowhere in the from clause or join clause.
the model is GuardiansStudent, not GuardiansStudents.

Categories