Find models through has_many relationship

I’m using AR and have 3 tables: users, devices with a users_devices table (user_id, device_id) to define the HAS_MANY relationship between them.

Device relations():

‘users’ => array(self::MANY_MANY, ‘User’, ‘users_devices(device_id, user_id)’),

User relations():

‘devices’ => array(self::MANY_MANY, ‘Device’, ‘users_devices(user_id, device_id)’),

What I’m looking for is the simplest method of finding a device from its id ( that belongs to a specific user ( via AR.

The scenario is a REST API is querying for a device, but I want to verify the device is owned by the user for security reasons.

Something like this is the idea:

$device = Devices::model()->findByPk($deviceId)->having(

array('user_id' => $userId));

Thanks in advance for any help, I’ve been researching this for a while and can’t find an elegant solution.

I think something like this should works:



    'condition'=>'userId=:userId AND deviceId=:deviceId',

    'params'=>array(':userId'=>$userId, 'deviceId'=$deviceId),


That didn’t quite work, but led me to this:

$device = Device::model()->with('users')->find(array(

    'condition' => 'user_id = :userId AND device_id=:deviceId',

    'params' => array(':userId' => Yii::app()->user->id, ':deviceId' => $_GET['id'])));

Which does work. Thanks!

Tbh I think you’ve overcomplicated it, database joins are not always cheap operations either. Why not something like?

$device = Device::model()->findByPk( $deviceId );

if ( $device->user_id != Yii::app()->user->id )


    throw new CHttpException( 403, 'You are not authorised to view this device' );



Doesn’t this:


Result in a join anyway?

I think your code is still more concise than the previous example… but performance wise shouldn’t it be similar?