获取所有收藏的记录

i have three tables

1) tbl_users -> id, name

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

2) tbl_favorites -> id, user_id, entry_id

I just want to fetch out all favorite entries of any user using Yii.

I am using dataprovider to achieve it and it gives all records of Entries table but i want to to show only those records which are added in favorites table.

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

plz help.


i just got mysql query for the same purpose but want to implement in yii style

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

The key to solve this is by correctly defining your Models-Relations (& this wiki post is also good), I am not sure of your business logic but i will assume the following:

  1. User has-many Entry
  2. User has-many Favorite
  3. Entries belongs-to User
  4. Entry has-one Favorite
  5. Favorite belongs-to Entry
  6. Favorite belongs-to User

Tip: Name your relations so it make sense later, e.g #1 should be entries while #3 should be entry

So, having a user_id you need to:

  1. Fetch User record
  2. Fetch that's user favorites
  3. For all the results from (2), fetch corresponding entries

The code will look something like:

$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