Retrieving Records Based On Field In Related Model - cakephp

I have an employees table with status that is active, new and resigned. In my drop down menu for the application i have all 3 different statuses that is active, new and resigned,now i wanna link to each different status, that is when i click on active it only shows me the active users in the employee table.
Please not status table is linked to the employees table.
Thank you in advance.

$records = $this->Employee->find('all', array(
'recursive' => -1,
'joins' => array(
array(
'table' => 'status',
'alias' => 'Status',
'type' => 'INNER',
'conditions' => 'Employee.status = Status.id'
)
),
'fields' => array('Employee.field1', 'Employee.field2'),
'conditions' => array('Status.id' => 'your_status_id'),
)
);

Related

How to write a mysql query in cakephp referencing different tables

I have the tables USERS(id, email), MAIL(id, message, receiver, user_id), SERVICES(id, service, user_id)...
A user posts a service, the another user replies to that service through the mail. I want to write a query that will retrieve the email of the user that posted that particular service from USERS and capture it in the receiver field in MAIL when someone replies to the service.
I'm fairly new to cake, and have no idea where to go from here
$receiver = $this->User->find('first',array(
'conditions' => array(
'Users.user_id' => 'Services.user_id',
)
));
SQL Query
SELECT u.email FROM users AS u, services AS s WHERE s.user_id = u.id LIMIT 0 , 30
Assuming you have User.php model, create one action as shown below
function getData(){
$options = array(
//'conditions' => array(‘User.user_id’=>9),
'joins' => array(
array(
'alias' => 'Service',
'table' => ‘services’,
'type' => 'LEFT',
'conditions' => array(
'Service.user_id = User.id',
),
),
array(
'alias' => 'Mail',
'table' => ‘mail',
'type' => 'LEFT',
'conditions' => array(
'Mail.user_id = User.id',
),
)
),
'fields' => array('User.email'),
'limit'=>10
);
$returnData = $this->find('all',$options);
return $returnData;
}
From controller call this method as
$data = $this->User->getData();
print_r($data);
Hope it will solve your problem!

How to find by conditions in two joining tables in CakePHP

In my CakePHP app I have three tables:
Businesses, Towns and Categories.
A business can belong to multiple towns and multiple categories so I have created joining tables and hasMany and belongsTo relationships. Everything works fine when finding businesses by either Town or Category by using the Town or Category model to search, but I am completely stuck when I want to search for businesses in a certain town AND a certain category, eg. Plumbers in London.
The associations just don't seem to work when searching with the Business model and I get column not found errors when trying to use the associated tables. I would think that this would be along the lines of what needs to be done, but I can't get it to work:
$this->set('listings', $this->Business->find('all', array(
'conditions' => array(
'Business.approved' => 1,
'BusinessesCategory.category_id' => $id,
'BusinessesTown.town_id' => $town_id,
'Business.sasite' => 1
)
You need to join the tables to do that.
I will put above a example how has to work with category and you can do the town yourself.
$this->Business->find("all", array(
"joins" => array(
array(
"table" => "businness_categories",
"alias" => "BusinessesCategory",
"type" => "LEFT",
"conditions" => array(
"Businesses.id = BusinessesCategory.business_id"
)
),
array(
"table" => "categories",
"alias" => "Category",
"type" => "LEFT",
"conditions" => array(
"BusinessesCategory.category_id = Category.id"
)
)
),
'conditions' => array(
'Business.approved' => 1,
'Category.id' => $id,
)
));
You also could use a behavior to do that for you:
https://github.com/Scoup/SuperJoin
Hi I had a very similar setup and the same problem. This is how I would solve your problem:
As you dont give away to much of your code I make some assumptions:
- You implemented your search method in the BusinessController
- Your search argument for the town is stored in vaiable $where and the one for Category is stored in $what
Code if you only have conditions for one table
$this->Businesses->Town->recursive = -1;
....
$options['joins'] = array(
array('table' => 'towns',
'alias' => 'Town',
'type' => 'inner',
'conditions' => array(
'Business.town_id = Town.id',
)
)
);
$options['conditions'] = array(
'Town.townName' => $where
);
$result = $this->Business->find('all', $options);
Code if you have conditions for two table
$this->Businesses->Town->recursive = -1;
$this->Businesses->Category->recursive = -1;
....
$options['joins'] = array(
array('table' => 'towns',
'alias' => 'Town',
'type' => 'inner',
'conditions' => array(
'Business.town_id = Town.id',
)
),
array('table' => 'categories',
'alias' => 'Category',
'type' => 'inner',
'conditions' => array(
'Business.category_id = category.id',
)
)
);
$options['conditions'] = array(
'Town.townName' => $where,
'Category.categoryName' => $what
);
$result = $this->Business->find('all', $options);
You can use
$this->Business->find('all', array(
'conditions' => array(
'AND' => array(
'BusinessesTown.town_id' => $town_id,
'BusinessesCategory.category_id' => $id
)
),
'recursive' => 2
));

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 table joining two tables issue

Im new to cakePHP and the whole table relations concept is very confusing!
I have 2 tables, competencies and competenceRatings. competencies stores a list of names with ids.
competencies
------------
id
name
And users can select various competencies from this table and rate them and their ratings are stored into competenceRatings table.
competenceRatings
-----------------
id
competence_id
user_id
rating
I want to be able to get the names of competencies for which a user have NOT made any ratings into competenceRatings table. i.e., I need list of names from competencies table for which there are no entries in comptenceRatings table(for given user_id).
I tried competencies->hasMany->competenceRatings, competenceRatings->belongsTo->competencies relations.
$competencies = $this->Competence->CompetenceRating->find('all',array('CompetenceRating.user_id' => $userId,'CompetenceRating.competence_id !=' => 'Competence.id'));
But no use!
Does this result require any other relations? Or can i just join tables using joins condition in find query?
Thanks.
EDIT
This method worked:
$options['joins'] = array(
array(
'table' => 'competence_ratings',
'alias' => 'CompetenceRating',
'type' => 'LEFT OUTER',
'conditions' => array(
'Competence.id = CompetenceRating.competence_id',
'CompetenceRating.user_id' => $userId
)
)
);
$options['conditions'] = array( 'CompetenceRating.competence_id'=> null );
Try this
Joining tables
$data = $this->Competence->find('all', array('joins' => array(
array(
'table' => 'competenceRatings',
'alias' => 'CompetenceRating',
'type' => 'inner',
'foreignKey' => false,
'conditions'=> array('CompetenceRating.competencie_id = Competence.id')
),
array(
'table' => 'competencies',
'alias' => 'Competence',
'type' => 'inner',
'foreignKey' => false,
'conditions'=> array(
'Competence.id = MarkersTag.tag_id',
'Competence.user_id' => $user_id
)
)
)));

Trying to get "City" data from Event->Venue->City using 'contain' in CakePHP

I'm trying to return a list of events, and include the city where it's taking place. The city is only associated through the Event's Venue though.
Below is the code I'm using. It returns all the correct data, but it doesn't return ANY city data (other than the city_id field in Venue - which I'm not sure why it's returning).
Associations:
Event belongsTo Venue
Venue hasMany Event
Venue belongsTo City
City hasMany Venue
Code:
$this->Event->Behaviors->attach('Containable');
$events = $this->Event->find('all', array(
'limit' => 5,
'order' => 'Event.created DESC',
'fields' => array(
'name',
'description',
'phone',
'price_general',
'price_child',
'price_adult',
'price_child',
'tickets_url'
),
'contain' => array(
'Venue' => array(
'fields' => array(
'name',
'address',
'city_id',
),
'City' => array(
'fields' => array(
'City.name',
'state'
),
'conditions' => array(
'City.id' => 'Venue.city_id'
)
)
),
'Schedule' => array(
'fields'=>array(),
'Date' => array(
'conditions'=>array(
'Date.start >=' => $start_date,
'Date.start <=' => $end_date,
)
)
)
),
));
Bonus answer: (that I have currently asked in another StackOverflow question) - The Date conditions are supposed to filter which events show up, but instead, they're only filtering which Date data to show.
WORKING ANSWER: (thanks bancer)
$this->Event->recursive = -1;
$options['joins'] = array(
array('table' => 'schedules',
'alias' => 'Schedule',
'type' => 'LEFT',
'conditions' => array(
'Event.id = Schedule.event_id',
)
),
array('table' => 'dates',
'alias' => 'Date',
'type' => 'LEFT',
'conditions' => array(
'Date.schedule_id = Schedule.id',
)
)
);
$options['fields'] = array(
'Event.name',
'Schedule.start_date',
'Date.start',
);
$options['limit'] = 5;
$events = $this->Event->find('all', $options);
I would recommend to avoid using Containable. It generates too many queries in some cases. A better way for complex queries is to join tables "manually".
Another option I would consider at the first place is to search through 'Venue' model without using Containable like this: $this->Event->Venues->find('all', ...). As Venues directly associated with Cities and Events there should be possible to get what you want without extra complexities.
Update: take a look at the question How to change the sequence of 'joins' in CakePHP?
instead of containable, did you try including the city data in fields itself by fields=> array('','','City.name)

Resources