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:
has-many
Entryhas-many
Favoritebelongs-to
Userhas-one
Favoritebelongs-to
Entrybelongs-to
UserTip: 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:
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