Relational active record question

I have a table called tbl_message and another one called tbl_user. I’d like to create relations that set up the tbl_message table in a way that id_to and it_from (both fields from the tbl_message) are assigned to id from the tbl_user. How would I set this up in the message model? Is there a way to have gii do this automatically or will I need to change the model manually?



If you create your foreign keys properly when you create the database, when you create your model using gii, it should create the relations automatically.

However, if not, just add the following to you Message model

    public function relations()


        return array(

            'userTo' => array(self::BELONGS_TO, 'User', 'id_from'),

            'userFrom' => array(self::BELONGS_TO, 'User', 'id_to'),



Ps: I use MySQLWorkBench to create my DB, it works wonders :)

Thanks. In what way would the database have to be set up correctly so that YII recognizes it automatically?


I’m not sure :)

The way i do it is use mysqlworkbench to create my DB and foreign keys, export it, then run the sql script in phpmyadmin to create the tables.

Feel free to ask if you aren’t sure how to do it in mysqlworkbench, I don’t know much, but I’ve figured out enough to do this :)