Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • How to join table in cakephp

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 158
    Comment on it

    Most of cakephp developer write custom query to join two table of database but cakephp provides best facility to join more than one two table in single query using association .

    Let see an Example:-

    SELECT *
    FROM `messages`
    INNER JOIN users ON messages.from = users.id
    WHERE messages.to = 4
    ORDER BY messages.datetime DESC
    

    messages table with a Message model
    users table with User model
    and want to retrieve information from both tables in one query. The users.id field is the same as the messages.from field, so that's what the join is on.
    I am doing it in my MessagesController so it would need to be something like:

    $this->Message->find();
    

    You would create a relationship with your User model and Messages Model, and use the containable behavior

    class User extends AppModel {
        public $actsAs = array('Containable');
        public $hasMany = array('Message');
    }
    
    class Message extends AppModel {
        public $actsAs = array('Containable');
        public $belongsTo = array('User');
    }
    

    You need to change the messages.from column to be messages.user_id so that cake can automagically associate the records for you.
    Then you can do this from the messages controller:

    $this->Message->find('all', array(
        'contain' => array('User')
        'conditions' => array(
            'Message.to' => 4
        ),
        'order' => 'Message.datetime DESC'
    ));

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: