Yii Framework Forum: Fetch Data With Mutiple Models - Yii Framework Forum

Jump to content

Page 1 of 1
  • You cannot start a new topic
  • You cannot reply to this topic

Fetch Data With Mutiple Models Rate Topic: -----

#1 User is offline   YiiSchool 

  • Newbie
  • Yii
  • Group: Members
  • Posts: 1
  • Joined: 14-May 13

Posted 14 May 2013 - 07:48 AM

I'm trying to fetch data from the database with an innerjoin and criteria. I want to have al the result of the users and the videos.

For now i'm using the createCommand:

public function getRelatedByUser($users_id){

$videos = Yii::app()->db->createCommand()
->select('*')
->from('videos')
->join('users', 'videos.users_id = users.id')
->where('videos.users_id = :userId AND Active=:active'
, array(':userId' => $users_id, ':active' => TRUE))
->order('Date desc')
->limit(5)
->queryAll();

return $videos;
}

But i want to use the command with the yii model like:

public function getRelatedByUser($users_id){

$criteria=new CDbCriteria;
$criteria->select = '*';
$criteria->alias = 'videos';
$criteria->join = 'INNER JOIN users ON videos.users_id = users.id';
$criteria->condition = 'users.id = :userID AND Active=:active';
$criteria->params = array (
':userID' => $users_id,
':active' => TRUE,
);
return Videos::model()->findAll($criteria);
}

But the problem is, when i use the code above, i get only the values of Videos, because i use the Videos::model()...

Now i was wondering of there's away to use multiple models, something like:

return VideosAndUsers::model()->findAll($criteria); or return All::model()->findAll($criteria);


please some help :)
0

#2 User is offline   Ghanshyam 

  • Junior Member
  • Pip
  • Yii
  • Group: Members
  • Posts: 41
  • Joined: 18-March 13
  • Location:Ahmedabad

Posted 14 May 2013 - 08:59 AM

hi,

you have to write t.* and u.*

$videos = Yii::app()->db->createCommand()
->select('t.*,u.*')
->from('videos t')
->join('users u', 't.users_id = u.id')
->where('t.user_id= :userid AND t.active= :active',array(':userid'=>$users_id,':active'=>TRUE))
->order('Date desc')
limit(5)
->queryAll();

0

#3 User is offline   Tsunami 

  • Standard Member
  • PipPip
  • Yii
  • Group: Members
  • Posts: 150
  • Joined: 16-February 12

Posted 14 May 2013 - 03:49 PM

Did you set up the relations() method in your Videos and Users models? If so, this is how to get the last 5 videos with their user:

$videos = Videos::model()->with('user')->findAll(array(
  'condition'=>'user.Active = 1',
  'limit'=>5,
  'order'=>'t.Date desc',
));

foreach($videos as $video)
{
  echo $video->user->username;
}


If you have an "active" scope in your Users model you can even remove 'condition' and use ->with('user:active') instead.

All of this is explained on Working with Databases: Relational Active Record.
0

Share this topic:


Page 1 of 1
  • You cannot start a new topic
  • You cannot reply to this topic

1 User(s) are reading this topic
0 members, 1 guests, 0 anonymous users