Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6642013
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 25, 20262026-05-25T23:52:46+00:00 2026-05-25T23:52:46+00:00

I have 2 basic models in my CakePHP application: User and Login. A user

  • 0

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?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-25T23:52:47+00:00Added an answer on May 25, 2026 at 11:52 pm

    UPDATED ANSWER IN RESPONSE TO COMMENTS

    With a belongsTo relationship, the foreign key should be in the current model.

    This means that if you want to have a relationship where User belongsTo LastLogin, the users table should have a last_login_id field.

    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 the fields key. 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:

    Array
    (
        [User] => Array
            (
                [id] => 1
                [name] => user1
                [last_login] => 2011-05-01 14:00:00
            )
        [Login] => Array
            (
                [0] => Array
                    (
                        [id] => 1
                        [user_id] => 1
                        [created] => 2011-05-01 12:00:00
                    )
                [1] => Array
                    (
                        [id] => 2
                        [user_id] => 1
                        [created] => 2011-05-01 13:00:00
                    )
                [2] => Array
                    (
                        [id] => 3
                        [user_id] => 1
                        [created] => 2011-05-01 14:00:00
                    )
            )
    )
    

    If you don’t use the Model::afterFind() callback your results will look more like this (Login array snipped to save space):

    Array
    (
        [User] => Array
            (
                [id] => 1
                [name] => user1
            )
    
        [0] => Array
            (
                [last_login] => 2011-05-01 14:00:00
            )
    )
    

    Example code:

    users table:

    CREATE TABLE `users` (
      `id` int(11) NOT NULL AUTO_INCREMENT,
      `name` varchar(255) NOT NULL,
      PRIMARY KEY (`id`)
    )
    

    logins table:

    CREATE TABLE `logins` (
      `id` int(11) NOT NULL AUTO_INCREMENT,
      `user_id` int(11) NOT NULL,
      `created` datetime DEFAULT NULL,
      PRIMARY KEY (`id`)
    )
    

    User model:

    class User extends AppModel {
        var $name = 'User';
        var $hasMany = array('Login');
        var $hasOne = array(
            'LastLogin' => array(
                'className' => 'Login',
                'fields' => array('MAX(LastLogin.created) as last_login')
            )
        );
    
        // This takes the last_login field from the [0] keyed array and puts it into 
        // [User]. You could also put this into your AppModel and it would work for 
        // all find operations where you use an SQL function in the 'fields' key.
        function afterFind($results, $primary=false) {
            if (!empty($results)) {
                foreach ($results as $i => $result) {
                    if (!empty($result[0])) { // If the [0] key exists in a result...
                        foreach ($result[0] as $key => $value) { // ...cycle through all its fields...
                            $results[$i][$this->alias][$key] = $value; // ...move them to the main result...
                        }
                        unset($results[$i][0]); // ...and finally remove the [0] array
                    }
                }
            }
            return parent::afterFind($results, $primary=false); // Don't forget to call the parent::afterFind()
        }
    }
    

    Users controller:

    class UsersController extends AppController {
        var $name = 'Users';
    
        function index() {
            $this->autoRender = false;
            pr($this->User->find('all'));
        }
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm new with cakephp .. sorry, if my question seems basic.. I have models:
I have a basic FK to user, call it owner class Baz(models.Model): owner =
I have a fairly basic set of models where a 'Project' has one 'Owner'.
I have developed a CakePHP application that does basic CRUD on a series of
I have a very basic model: class Link(models.Model): title = models.CharField(max_length=250, null=False) user =
I have a basic Django model like: class Business(models.Model): name = models.CharField(max_length=200, unique=True) email
I have a very basic model - User I am trying to do some
Lets say we have some basic AR model. class User < ActiveRecord::Base attr_accessible :firstname,
I am new to MVC and have a grasp of the basic model, but
I have basic hello word example of Prime Faces. I have created dynamic web

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.