CakePHP 2.x retrieve/query using data in HABTM join table - php

I have 2 tables joined by a HABTM relationship. portfolios and assets. The join table is portfolios_assets.
I wish to have an extra field in the join table, rebalance_date such that I can query the assets in a portfolio for a given date. How would I construct a find such that I can determine the most recent date and only return the assets for that date.
So, in my Portfolio model I might have:
$params = array(
'conditions' => array(
'Portfolio.id' => 5,
'?.rebalance_date' => '2013-11-01' //no model name for this field as it's in the join table
),
'order' => array(...)
);
$result = $this->find('all', $params);
In the above example, I just keyed in a date. I'm not sure how I would retrieve the latest date without writing a raw query in Cake. (I could do SELECT rebalance_date FROM portfolios_assets ORDER BY rebalance_date DESC LIMIT 1; but this is not following Cake's convention)

You need to use the hasMany through model: http://book.cakephp.org/2.0/en/models/associations-linking-models-together.html#hasmany-through-the-join-model
You would need to create another model eg PortfolioAssests and the table would need to be portfolio_assets not portfolios_assets.
Then you should be able to use:
$assets = $this->Assets->find('all', array(
'conditions' => array(
'Portfolio.id' => 5,
'PortfolioAsset.rebalance_date' => '2013-11-01'
)
));

Related

Cakephp count containable records

Cakephp 2.6
Schools hasMany Pupils and I am running a containable query from the Schools model. In this query I want to count the number of pupils each school has but I can't get it to work.
I've tried using the following virtual field, but it doesn't work
$this->virtualFields['total'] = 'COUNT(Pupil.id)';
and the following is giving inaccurate counts
$contain = array(
'Pupil' => array(
'fields' => array(
'CONT(Pupil.id) AS total'
)
),
);
I don't want to use counterCache as data can be mass imported to both tables outside of the framework so I can't rely on it to update the count field.
How can I get this count to run correctly?
Try to add grouping by Schools:
$contain = array(
'Pupil' => array(
'fields' => array(
'CONT(Pupil.id) AS total'
),
'group' => array('Pupil.school_id') // doesn't really know how you called `school` relation column...
),
);

cakephp - getting joins correct

I'm a bit of a newbie and I'm having trouble getting my cakephp query correct.
I have a users table and users hasmany rotas. The rotas table looks like
monday_am
monday_pm
tuesday_am
etc
and if the user is due to be in on monday_pm for example, then that field will have 1. Otherwise 0.
I want to get all the users who belong to a particular room, have deregistered=0 and - and this is where I'm having the problem - who have a rota where (for example) tuesday_am = 1
So I have the code:
$options['conditions'] = array('User.room_id'=>$room_id, 'User.deregistered'=>0, 'User.request'=>0);
$options['joins'] = array(
array('table' => 'rotas',
'alias' => 'rota',
'type' => 'INNER',
'conditions' => array('rota.'.$todaysDay.'_'.$amPm => 1)
)
);
$usersToday = $this->User->find('all', $options);
If I don't try the join then I get a nice small list of users like I expect. If I try the join I get 100s of results which are mostly duplicates!
How can I get just one record of a user who has the required conditions in the Users table as well as the Rotas table, and how come doing the join as I have causes so many results?!?
thanks
Assuming you have a column in your rota table called user_id, you can make your Rota model like this:
class Rota extends Model
{
public $belongsTo = array('User');
}
Then in your controller, you can query the Rotas and get the user from it.
$users = $this->Rota->find('all', array(
'fields' => array('DISTINCT (User.id)' /* add more fields for selection */ ),
'conditions' => array(
'User.room_id'=>$room_id,
'User.deregistered'=>0,
'User.request'=>0,
'Rota.'.$todaysDay.'_'.$amPm => 1
)
));

Lithium (li3) order and limit hasMany related data

Using the Lithium framework, I have two model classes, Post and Image. They are related via a hasMany relationship.
//Post.php
class Post extends \lithium\data\Model {
public $hasMany = array('Image');
}
In one of my queries in my PostsController, I am attempting to find a Post with Images that are sorted by an order and have a limit. However the order and limit options on the Images are being ignored. Here is what my query looks like:
//PostsController.php
$post = Post::find('first', array(
'with'=>array(
'Image'=>array(
'order'=>array('position'=>'ASC'),
'limit'=>3
)
),
'conditions'=>array(
'Post.id'=>'some-id-value'
)
));
This particular query is returning the post with ALL of its related images, not sorted by 'position.' For example if this post had 10 images related to it, all 10 images are being returned with it instead of just the limit of 3, sorted by position.
In general, the idea is that I want to be able to order and limit a model's related hasMany data. Is this possible with the hasMany relationship in Lithium or will hasMany always return all the related data no matter what? Clearly what I am attempting is not the correct way of doing it.
Here's how you can use ORDER BY with Lithium Relationships ...
$table1_table2 = Table1::find('all', array(
'conditions' => array('Table1.foo' => 'bar'),
'with' => array('Table2'),
'order' => array('Table2.title'),
'limit' => 3
));
Note the 'Table2.title' which wll result in something like ...
SELECT ... ORDER BY Table2.title;
The ASC is implied in this case, but you can pass ASC or DESC as well.
Do you can add a final query wich do you need? As I know, MySQL can't limit and order in JOINs at all, only in subqueries.
So, in this case, 2 requests is better than 1 join:
first Post::find(...conditions...) then
$images = Image::find(array(
'order' => array('post_id','position'),
'limit' => 3,
'conditions' => array(
'post_id' => $array_of_post_id_from_first_query
)
);

CakePHP - problem with HABTM paginate query

Tables
restaurants
cuisines
cuisines_restaurants
Both restaurant and cuisine model are set up to HABTM each other.
I'm trying to get a paginated list of restaurants where Cuisine.name = 'italian' (example), but keep getting this error:
1054: Unknown column 'Cuisine.name' in 'where clause'
Actual query it's building:
SELECT `Restaurant`.`id`, `Restaurant`.`type` .....
`Restaurant`.`modified`, `Restaurant`.`user_id`, `User`.`display_name`,
`User`.`username`, `User`.`id`, `City`.`id`,`City`.`lat` .....
FROM `restaurants` AS `Restaurant` LEFT JOIN `users` AS `User` ON
(`Restaurant`.`user_id` = `User`.`id`) LEFT JOIN `cities` AS `City` ON
(`Restaurant`.`city_id` = `City`.`id`) WHERE `Cuisine`.`name` = 'italian'
LIMIT 10
The "....." parts are just additional fields I removed to shorten the query to show you.
I'm no CakePHP pro, so hopefully there's some glaring error. I'm calling the paginate like this:
$this->paginate = array(
'conditions' => $opts,
'limit' => 10,
);
$data = $this->paginate('Restaurant');
$this->set('data', $data);
$opts is an array of options, one of which is 'Cuisine.name' => 'italian'
I also tried setting $this->Restaurant->recursive = 2; but that didn't seem to do anything (and I assume I shouldn't have to do that?)
Any help or direction is greatly appreciated.
EDIT
models/cuisine.php
var $hasAndBelongsToMany = array('Restaurant');
models/restaurant.php
var $hasAndBelongsToMany = array(
'Cuisine' => array(
'order' => 'Cuisine.name ASC'
),
'Feature' => array(
'order' => 'Feature.name ASC'
),
'Event' => array(
'order' => 'Event.start_date ASC'
)
);
As explained in this blogpost by me you have to put the condition of the related model in the contain option of your pagination array.
So something like this should work
# in your restaurant_controller.php
var $paginate = array(
'contain' => array(
'Cuisine' => array(
'conditions' => array('Cuisine.name' => 'italian')
)
),
'limit' => 10
);
# then, in your method (ie. index.php)
$this->set('restaurants', $this->paginate('Restaurant'));
This fails because Cake is actually using 2 different queries to generate your result set. As you've noticed, the first query doesn't even contain a reference to Cuisine.
As #vindia explained here, using the Containable behavior will usually fix this problem, but it doesn't work with Paginate.
Basically, you need a way to force Cake to look at Cuisine during the first query. This is not the way the framework usually does things, so it does, unfortunately, require constructing the join manually
. paginate takes the same options as Model->find('all'). Here, we need to use the joins option.
var $joins = array(
array(
'table' => '(SELECT cuisines.id, cuisines.name, cuisines_restaurants.restaurant_id
FROM cuisines_restaurants
JOIN cuisines ON cuisines_restaurants.cuisines_id = cuisines.id)',
'alias' => 'Cuisine',
'conditions' => array(
'Cuisine.restaurant_id = Restaurant.id',
'Cuisine.name = "italian"'
)
)
);
$this->paginate = array(
'conditions' => $opts,
'limit' => 10,
'joins' => $joins
);
This solution is a lot clunkier than the others, but has the advantage of working.
a few ideas on the top of my mind:
have you checked the model to see if the HABTM is well declared?
try using the containable behavior
in none of those work.. then you could always construct the joins for the paginator manually
good luck!
Cuisine must be a table (or alias) on the FROM clausule of your SELECT.
so the error:
1054: Unknown column 'Cuisine.name' in 'where clause'
Is just because it isn't referenced on the FROM clausule
If you remove the Feature and Event part of your HABTM link in the Restaurant model, does it work then?
Sounds to me like you've failed to define the right primary and foreing keys for the Cuisine model, as the HABTM model is not even including the Cuisine tabel in the query you posted here.

How can I find all records for a model without doing a long list of "OR" conditions?

I'm having trouble composing a CakePHP find() which returns the records I'm looking for.
My associations go like this:
User ->(has many)-> Friends ,
User ->(has many)-> Posts
I'm trying to display a list of all a user's friends recent posts, in other words, list every post that was created by a friend of the current user logged in.
The only way I can think of doing this is by putting all the user's friends' user_ids in a big array, and then looping through each one, so that the find() call would look something like:
$posts = $this->Post->find('all',array(
'conditions' => array(
'Post.user_id' => array(
'OR' => array(
$user_id_array[0],$user_id_array[1],$user_id_array[2] # .. etc
)
)
)
));
I get the impression this isn't the best way of doing things as if that user is popular that's a lot of OR conditions. Can anyone suggest a better alternative?
To clarify, here is a simplified version of my database:
"Users" table
id
username
etc
"Friends" table
id
user_id
friend_id
etc
"Posts" table
id
user_id
etc
After reviewing what you have rewritten, I think I understand what you are doing. Your current structure will not work. There is no reference in POSTS to friends. So based on the schema you have posted, friends CANNOT add any POSTS. I think what you are trying to do is reference a friend as one of the other users. Meaning, A users FRIEND is actually just another USER in the USERS table. This is a self referential HABTM relationship. So here is what I would propose:
1- First, make sure you have the HABTM table created in the DB:
-- MySQL CREATE TABLE users_users ( user_id char(36) NOT NULL,
friend_id char(36) NOT NULL );
2- Establish the relationships in the User model.
var $hasAndBelongsToMany = array(
'friend' => array('className' => 'User',
'joinTable' => 'users_users',
'foreignKey' => 'user_id',
'associationForeignKey' => 'friend_id',
'unique' => true,
),
);
var $hasMany = array(
'Post' => array(
'className' => 'Post',
'foreignKey' => 'user_id'
),
);
3- use the scaffolding to insert a few records, linking friends and adding posts.
4- Add the view record function to the Users controller:
function get_user($id)
{
$posts = $this->User->find('first', array(
'conditions' => array('User.id' => $id),
'recursive' => '2'
));
pr($posts);
}
5- Now you can query the User table using recursive to pull the records using the following command:
http://test/users/get_user/USER_ID
6- Your output will show all of the records (recursively) including the friends and their posts in the returned data tree when you pr($posts)
I know this is a long post, but I think it will provide the best solution for what you are trying to do. The power of CakePHP is incredible. It's the learning curve that kills us.
Happy Coding!
If Post.user_id points to Friend.id (which wouldn't follow the convention btw) then it would be
$posts = $this->Post->find('all',array(
'conditions' => array(
'Post.user_id' => $user_id_array
)
);
which would result in .. WHERE Post.user_id IN (1, 2, 3) ..
Depending on your setup, it might be quicker to run two queries rather than trying to chain them together via the Cake stuff. I'd recommend adding something like getFriendsPosts() in the Users model.
<?php
class UserModel extends AppModel {
// ... stuff
function getFriendsPosts( $user_id )
{
$friends = $this->find( ... parameters to get user IDs of all friends );
// flatten the array or tweak your params so they fit the conditions parameter. Check out the Set class in CakePHP
$posts = $this->find( 'all', array( 'conditions' => array( 'User.id' => $friends ) ) );
return $posts;
}
}
?>
Then to call it, in the controller just do
$friends = $this->User->getFriendsPosts( $this->Auth->User('id') );
HTH,
Travis
Isn't CakePHP already generating the efficient code of:
SELECT * from Posts WHERE user_id IN (id1, id2 ...)
if not, you can do
$conditions='NULL';
foreach($user_id_array as $id) $conditions.=", $id";
$posts = $this->Posts->find('all', array(
'conditions' => "Post.user_id IN ($conditions)",
));
If your models are properly associated, Cake will automatically retrieve related model records. So, when you search for a specific user, Cake will automatically retrieve related friends, and related posts of these friends. All you need to do is set the recursion level high enough.
$user = $this->User->find('first', array('conditions' => array('User.id' => $id), 'recursive' => 2));
debug($user);
// gives something like:
array(
User => array()
Friend => array(
0 => array(
...
Post => array()
),
1 => array(
...
Post => array()
)
)
)
All you need to do is extract the posts from the user's friends, which is as easy as:
$postsOfFriends = Set::extract('/Friend/Post/.', $user);

Categories