Declaring Relationship - Which one should be the foreign key?

Please take a look at the example database scheme.

Here is the demo code to declare the relationship:

class Post extends CActiveRecord 

{ 	......  	

 public function relations()   


 return array(  

      	'author'=>array(self::BELONGS_TO, 'User', 'author_id'),   		

          'categories'=>array(self::MANY_MANY, 'Category', 'tbl_post_category(post_id, category_id)'),);  



My question is: for this relationship

'author'=>array(self::BELONGS_TO, 'User', 'author_id')

Can I replace ‘author_id’ with ‘id’? author_id is in Post table, and id is in User table, and they all always the same.

If not, why?

Thank you!

Which column is the one that tells a post which user it belongs to?

The foreing key in Post table its author_id, it references id on the user table.

you cant replace it… or Post wont know who is its owner.

No, you can’t.

Because that relationship definition says that ‘author’ is a belongs-to relationship using author_id which points to ‘User’.

Read all about that here:


I’ve read it several times today, and my example is quoted from the guide.

class User extends CActiveRecord 

{ 	......   	

 	public function relations()	


         	return array('posts'=>array(self::HAS_MANY, 'Post', 'author_id'),  

      	                        'profile'=>array(self::HAS_ONE, 'Profile', 'owner_id'), );  



Your answer is clear to me, but I am confused again when look at the following code.

'posts'=>array(self::HAS_MANY, 'Post', 'author_id')

When it defines the relationship from User to Post, why the foreign key is still ‘author_id’ in the Post table? Why not ‘id’ in the User table?

Can I say the foreign key in a relationship, no matter from User to Post, or Post to User, should always be the key that refers to the PK in the other table?