获取所有收藏的记录

时间:2012-08-11 01:56:48

标签: php yii

我有三张桌子

1)tbl_users - > id,name

2)tbl_entries - > id,title,details,user_id

2)tbl_favorites - > id,user_id,entry_id

我只想使用Yii获取所有用户的所有喜欢的条目。

我正在使用dataprovider来实现它,它提供了条目表的所有记录,但我想只显示在收藏夹表中添加的那些记录。

$dataProvider = new CActiveDataProvider('Entries', array(
    'criteria' => $criteria,
    'pagination' => array(
        'pageSize' => 15,
    ),
    ));

帮助。


我只是为了相同的目的而获得了mysql查询,但希望以yii风格实现

SELECT * FROM tbl_entries, tbl_favorites  where tbl_entries.id = tbl_favorites.entry_id and tbl_favorites.user_id = xx

1 个答案:

答案 0 :(得分:0)

解决此问题的关键是正确定义Models-Relations(& this wiki post也不错),我不确定您的业务逻辑,但我会假设以下内容:

  1. 用户 has-many 条目
  2. 用户 has-many 收藏
  3. 条目 belongs-to 用户
  4. 条目 has-one 收藏
  5. 收藏 belongs-to 条目
  6. 收藏 belongs-to 用户
  7. 提示:为您的关系命名以便以后有意义,例如#1应该是条目而#3应该是条目

    所以,你需要user_id

    1. 获取用户记录
    2. 获取用户收藏夹
    3. 对于(2)的所有结果,获取相应的条目
    4. 代码看起来像:

      $user = User::model()->findByPk($user_id); //Fetch user record
      $favorites = $user->favorites; // Fetch the user favorites using relations #2 & #6
      
      // Getting entries
      $entries = array(); // empty array to store entries
      
      foreach($favorites as $fav) do
      {
        $entries[] = $fav->entry; // Fetch entry record using relations #4 & #5
      }
      ....
      // Pass $entries array to your view