CakePHP conditions for deep associations - cakephp

I have some deep associations using containable and need to filter back the results. For the sake of this question, let's say we are selling cars and want to narrow the results down by features.
Car hasmany make hasmany model HABTM features
$options = array(
'order' => array('Car.price'),
'contain' => array(
'make',
'model' => array(
'order' => 'Model.name ASC'
),
'features'
)
);
$cars = $this->Car->find('all', $options);
How would I go about excluding all cars that don't have power windows (Features.name != power_windows).

Containable is only suitable for you to specify what models you wanted to include when fetching data, but not limiting the parent model from fetching data at all. One obvious symptom is that sometimes your parent data may have some null contained data.
So to achieve it, I think we should use joins here so you can specify condition:
$options = array(
'order' => array('Car.price'),
'contain' => array(
'make',
'model' => array(
'order' => 'Model.name ASC'
),
'features'
),
'joins' => array(
array(
'table' => 'features',
'alias' => 'Feature',
'type' => 'LEFT',
'conditions' => array(
'Car.id = Feature.car_id'
)
)
),
'conditions' => array(
'Features.name !=' => 'power_windows',
)
);
But one drawback of this is that you might have duplicated Car due to joining. That's a separate issue ;)

Related

Select records which have atleast one hasMany relation row in Cakephp

I'm facing a problem with cakephp associations in Models.
I have to Select records which have atleast one hasMany reation row
Model
class Category extends AppModel
{
public $hasMany = array(
'Product' => array(
'className' => 'Product',
'foreignKey' => 'CategoryId',
)
);
}
Query
$categories = $this->Category->find('all');
I only needed the categories which have atleast one product entry
Categories Like : Shirts, Footwear, Glasses etc
Products like :
Small, medium, large (Shirts)
With Frame, UV protected (Glass)
So, i jus want to get Shirts and Glasses Categories only because for the above example there is no products for Footwear
Use counterCache or joins
Please refer to CakePHP - Find and count how many associated records exist
The most simple way with the best performance would be using a properly indexed counter cache field as shown in the linked answer.
Sice the linked answer is not an exact duplicate with respect to the join, here's some additional info, instead of using HAVING COUNT with the join you'd use a IS NOT NULL condition. Here's an (untested) example:
$this->Category->find('all', array(
'joins' => array(
array(
'table' => 'products',
'alias' => 'Product',
'type' => 'LEFT',
'conditions' => array('Category.id = Product.CategoryId')
)
),
'conditions' => array(
'Product.CategoryId IS NOT NULL'
)
'group' => 'Category.id'
));
Depending on the used DBMS and version you might get better performance using an inner join:
$this->Category->find('all', array(
'joins' => array(
array(
'table' => 'products',
'alias' => 'Product',
'type' => 'INNER',
'conditions' => array('Category.id = Product.CategoryId')
)
),
'group' => 'Category.id'
));

Containable behavior doesn't return deeper model association and selecting fields

I want to limit the fields returned by a deeper association using containable.
My associations:
Game hasMany Review
The paginate and containable code:
$this->paginate = array(
'conditions' => $conditions,
'fields' => array(
'Game.id', 'Game.name',
'Publisher.id', 'Publisher.name'
),
'contain' => array(
'Game' => array(
'Review' => array(
'fields' => array('Review.id', 'ROUND(AVG(Review.score),1)')
)
),
)
);
$games = $this->paginate('Game');
Currently, all of the fields in the Review table are returned. 'ROUND(AVG(Review.score),1)' is never returned. How can I specify what fields I want returned from the Review association?
SQL dumps for two search results using #theJetzah's answer. The first is a search with one game as a result and the second is a search returning three games.
SELECT `Review`.`id`, `Review`.`review_text`, `Review`.`score`, `Review`.`user_id`, `Review`.`game_id`, `Review`.`created`, `Review`.`platform_id`, (ROUND(AVG(`Review`.`score`),1)) AS `Review__average_score` FROM `videogamedb`.`reviews` AS `Review` WHERE `Review`.`game_id` = (55)
SELECT `Review`.`id`, `Review`.`review_text`, `Review`.`score`, `Review`.`user_id`, `Review`.`game_id`, `Review`.`created`, `Review`.`platform_id`, (ROUND(AVG(`Review`.`score`),1)) AS `Review__average_score` FROM `videogamedb`.`reviews` AS `Review` WHERE `Review`.`game_id` IN (55, 56, 57)
Not a full answer, but an attempt to get it working :)
Approach1 (UPDATE: Containable doesn't support 'group by')
First of all, try to add the 'Game' model to the $uses array of your Controller, if it is not included yet, and re-organise the pagination array (as previously suggested by Sam), so that you'll be pagination the Game model itself.
Then, It may help to create a virtual field for the calculated score, but the results of 'Review' need to be grouped, otherwise you'll not be able to calculate the average score.
I'm not able to test this, but it may worth trying
something like this;
public $uses = array(
'Game',
// other models
);
public function myfunction()
{
$this->Game->Review->virtualFields['average_score'] = 'ROUND(AVG(Review.score),1)';
$this->paginate = array(
'Game' => array(
'fields' => array(
'Game.id',
'Game.name',
'Publisher.id',
'Publisher.name'
),
'contain' => array(
'Review' => array(
'fields' => array(
'Review.game_id,
'Review.average_score',
),
'group' => array(
'Review.game_id,
),
)
)
)
);
// Conditions can be passed to paginate,
// that way you can specify 'paginate' at
// one place and don't have to modify it
// to include the conditions
$games = $this->paginate('Game', $conditions);
}
Alternative approach: Using joins and a database-view
Apparently, the Containable behavior doesn't like group-by clauses; See this ticket for more information: Containable behavior does not implement 'group' option
CakePHP allows you to manually specify a join: Joining Tables
To simplify things and to prevent having to add a 'group by' for all fields, create a simple database-view in your database;
CREATE VIEW review_scores AS
SELECT
game_id,
ROUND(AVG(score),1) AS average_score,
COUNT(id) AS total_reviews
FROM
reviews
GROUP BY
game_id;
If you're unfamiliar with this; a database 'view' is basically a 'stored query', which can be accessed as if it was a regular table. See Create View
Then, use a 'manual' join, using the newly created database-view as the source-table. In your case, this will look something like this;
$this->paginate = array(
'Game' => array(
'fields' => array(
'Game.id',
'Game.name',
'Publisher.id',
'Publisher.name',
'ReviewScore.average_score',
'ReviewScore.total_reviews',
),
'joins' => array(
array(
'table' => 'review_scores',
'alias' => 'ReviewScore',
'type' => 'LEFT',
'conditions' => array(
'ReviewScores.game_id = Game.id',
)
)
)
)
);
Hope this helps
I think your array is a configured a little wrong, try:
$this->paginate = array(
'Game' => array(
'conditions' => $conditions,
'fields' => array(
'Game.id', 'Game.name',
'Publisher.id', 'Publisher.name'
),
'contain' => array(
'Review' => array(
'fields' => array('Review.id', 'ROUND(AVG(Review.score),1)')
)
)
)
);
$games = $this->paginate('Game');
As an aside, from personal experience, specifying the fields in a query doesn't always speed it up (certainly for small number of fields), assuming this is the motive for doing so. It does reduce memory occupancy but this is only relative to original size of the record and the number of records returned.

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)

Only retrieve records with at least one association

This is pretty straightforward, but I guess I've never bumped into it before. I have a Page model that hasMany Comment. I'd like to pull all of the pages that have at least 1 comment, but eliminate pages with none. As I look at it, I realize that I'm not sure how to do that. I guess I could use ad hoc joins, but I'd rather use Containable, if that's possible. I've tried testing not null in the Comment conditions and one or 2 other things that were unlikely to work, but it seems like this should be possible.
What I get now, of course, is all pages and some of those page records have an empty Comment member. Be nice to skip passing around all of the extra cruft if I can do so.
My find call:
$pages = $this->Folder->Page->find(
'all',
array(
'contain' => array(
'Comment' => array(
'order' => array( 'Comment.modified DESC' ),
),
'Folder' => array(
'fields' => array( 'Folder.id' ),
),
),
'conditions' => array(
'Folder.group_id' => $id,
),
)
);
Thanks.
You have several approaches available other than ad-hoc joins:
Denormalize your dataset and add a has_comment flag to your pages table. Add 'Page.has_comment' => 1 to your conditions.
Run your query against Comment, with DISTINCT page_id.
$comments = $this->Folder->Page->Comment->find('all', array(
'conditions' => array('DISTINCT Comment.page_id'
'contain' => array(
'Page' => array(
'Folder'
)
)
);
First grab a distinct set of page ids from the comments table.
$page_ids = $this->Folder->Page->Comment->find('list', array(
'fields' => array('id', 'page_id'),
'conditions' => array('DISTINCT Comment.page_id'),
);
$pages = $this->Folder->Page->find('all', array(
'conditions' => array('Page.id' => $page_ids),
'contain' => array(
...
)
);

cakephp paginate multiple habtm

i have multiple habtm like these :
// User model
var $hasMany = array('Post');
// Post model
var $hasAndBelongsToMany = array('Category', 'Tag');
// Category model
var $hasAndBelongsToMany = array('Post');
// Tag model
var $hasAndBelongsToMany = array('Post');
I tried to fetch all post along with its user and tags (within a certain category), somehow if i fetch tags, the result was wrong.
$this->paginate = array
(
'Post' => array
(
'limit' => 2,
'fields' => array(
'Post.title', 'Post.content', 'Post.slug', 'Post.created',
'Tag.name',
'User.username', 'User.created', 'User.post_count', 'User.avatar_file_name'),
'joins' => array
(
array(
'table' => 'categories_posts',
'alias' => 'CategoriesPost',
'type' => 'inner',
'conditions'=> array('CategoriesPost.post_id = Post.id')
),
// FETCH USER
array(
'table' => 'users',
'alias' => 'User',
'type' => 'inner',
'conditions'=> array('Post.user_id = User.id')
),
// FETCH TAGS
array(
'table' => 'posts_tags',
'alias' => 'PostsTag',
'type' => 'inner',
'conditions'=> array('PostsTag.post_id = Post.id')
),
array(
'table' => 'tags',
'alias' => 'Tag',
'type' => 'inner',
'conditions'=> array('Tag.id = PostsTag.tag_id')
),
array(
'table' => 'categories',
'alias' => 'Category',
'type' => 'inner',
'conditions'=> array('Category.id = CategoriesPost.category_id', 'Category.slug' => $slug)
)
)
)
);
$posts = $this->paginate();
could anyone gimme a solution since i'm a newbie?
many thanks...
I've run into a similar problem, when trying to paginate a resultset using an associated model. I ended up having to manually bind my models together, run the query, and then unbind them in order to get Cake to contain the right data together. ( http://book.cakephp.org/view/86/Creating-and-Destroying-Associations-on-the-Fly )
You could also try the containable behaviour which will allow you to specify which models you want to include in your result set. Containable is core in 1.2+ ( http://book.cakephp.org/view/474/Containable ), otherwise you'll need to grab it yourself.
I'm not too sure on why you have such a gargantuan query there though. I would be more inclined to do something similar to the following.
$this->Model->recursive = 2;
$this->Model->paginate();
And let Cake get all the related data for me through my associations. Then I would adjust the return using a conditions array ( http://api.cakephp.org/class/controller#method-Controllerpaginate ) to specify the category.
Sorry it's not a defacto solution, but I'm a CakePHP amateur myself! You might find it easier to view the queries, results etc, using DebugKit, http://github.com/cakephp/debug_kit

Resources