YII积极记录加入

I am looking at YII for the first day, and i'm having some problems trying to work out the relations between some tables.

my table structure is as follows:

Pets: pet_id pet_name ....

Pet_Owner_Link pet_id owner_id

Owner: owner_id owner_name

How would I go about getting all of the pets that belong to an owner? Really struggling to get my head around the AR relations at the moment.

Per this comment by DD.Jarod on the Yii AR documentation page: http://www.yiiframework.com/doc/guide/1.1/en/database.arr#c970

"If you declare a many to many relationship, the order of keys inside the jointable declaration must be 'my_id, other_id':

class Post extends CActiveRecord
{
  public function relations()
  {
    return array(
        'categories'=>array(self::MANY_MANY, 'Category',
            'tbl_post_category(post_id, category_id)'),
    );
  }
}
class Category extends CActiveRecord
{
  public function relations()
  {
    return array(
        'Posts'=>array(self::MANY_MANY, 'Post',
            'tbl_post_category(category_id, post_id)'),
    );
  }
}

So your code would look like:

class Owner extends CActiveRecord
{
  public function relations()
  {
    return array(
        'pets'=>array(self::MANY_MANY, 'Pet',
            'tbl_post_category(pet_id, owner_id)'),
    );
  }
}
class Pet extends CActiveRecord
{
  public function relations()
  {
    return array(
        'owners'=>array(self::MANY_MANY, 'Post',
            'tbl_post_category(owner_id, pet_id)'),
    );
  }
}

Your problem may be that your primary keys for Pet and Owner by default should be id (not pet_id / owner_id). Yii may be getting confused if you don't clarify that your primary keys don't match the default naming convention / aren't setup as primary keys in the database. You can specify what your primary key is in a model like this:

public function primaryKey()
{
    return 'owner_id';
}

Finally, you would retrive the information like this:

$owner = Owner::model()->findByPk((int)$id);
foreach($owner->pets as $pet)
{
    print $pet->name;
}

I know this is not exactly what you ask, but this is how I do it.

Add this item in your relations() return in Owner model :

'all_pets'=>array(self::HAS_MANY, 'Pet_Owner_Link','owner_id'),

Add this item in your relations() return in Pet_Owner_Link model :

'pet'=>array(self::BELONGS_TO, 'Pet', 'pet_id'),

Then get a pet like this

$owner->all_pets[$i]->pet;