doujiaohuo1096 2012-04-13 14:24
浏览 8
已采纳

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.

  • 写回答

2条回答 默认 最新

  • drbii0359 2012-04-13 19:37
    关注

    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;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?