I have 2 basic models in my CakePHP application: User and Login. A user has a hasMany relation with Logins (i.e., a new login record is created everytime the user logs in).
Now, I want to make 2 relations from the User model to the Login model:
User hasMany Login
and
User hasOne lastLogin
This last relation should only include the last record of the Login model for the selected user.
I tried this as follows:
var $belongsTo = array
(
'LastLogin' => array
(
'className' => 'Login',
'order' => 'LastLogin.created DESC',
'limit' => 1
)
);
However, this doesn’t work. Any ideas on how to get this working?
UPDATED ANSWER IN RESPONSE TO COMMENTS
With a
belongsTorelationship, the foreign key should be in the current model.This means that if you want to have a relationship where User belongsTo LastLogin, the
userstable should have alast_login_idfield.In your case you probably want to use a hasOne relationship instead, and you’re going to have to use the
MAX()SQL function in thefieldskey. Note that getting the last_login works completely independently of your User hasMany Login relationship. So if all you want is the last login you can remove the hasMany relationship and just leave the hasOne.With the example code below you’ll get this:
Output of /users/index:
If you don’t use the Model::afterFind() callback your results will look more like this (Login array snipped to save space):
Example code:
users table:
logins table:
User model:
Users controller: