views:

327

answers:

1

I have a question about how to set up the relations between two models when they join to each other in two different regards.

I'll give an example of the problem I've got:

Users (id, name)
Messages (id, message, from_user_id, to_user_id)

(In my case, it's not users nor messages, but this hopefully illustrates the problem in a simpler way)

Users can send messages to each other, and each Message has a User who sent it and a User who will receive it. I'm trying to figure out the Model relations:

class User extends AppModel {
    var $hasMany = array("Message");
}

class Message extends AppModel {
    var $belongsTo = array("User");
}

I'm also not sure how the fields should be named in the database so CakePHP will pick up the relationship properly.

+1  A: 

I've been able to work it out with the relationship options:

class Message extends AppModel {
    var $belongsTo = array(
        "FromUser" => array(
              "className" => "User"
            , "foreignKey" => "from_user_id"
            , "type" => "INNER"
        ),
        "ToUser" => array(
              "className" => "User"
            , "foreignKey" => "to_user_id"
            , "type" => "INNER"
        )
    );
}

class User extends AppModel {
    var $hasMany = array(
        "MessageFrom" => array(
              "className" => "Message"
            , "foreignKey" => "from_user_id"
        ),
        "MessageTo" => array(
              "className" => "Message"
            , "foreignKey" => "to_user_id"
        )
    );
}

This question and answer was very helpful, too!

nickf