rdoherty
(Ryan Doherty)
August 5, 2011, 3:34am
1
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 (devices.id) that belongs to a specific user (users.id) 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.
ivica
(Ivica Nedeljkovic)
August 5, 2011, 4:51am
2
I think something like this should works:
$device=Devices::model()->with('users')->find(array(
'select'=>'userId'
'condition'=>'userId=:userId AND deviceId=:deviceId',
'params'=>array(':userId'=>$userId, 'deviceId'=$deviceId),
));
rdoherty
(Ryan Doherty)
August 5, 2011, 5:10am
3
Ivica:
I think something like this should works:
$device=Devices::model()->with('users')->find(array(
'select'=>'userId'
'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!
Say_Ten
(Yii)
August 5, 2011, 1:30pm
4
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' );
}
?
dniznick
(Dniznick)
August 5, 2011, 5:43pm
5
Doesn’t this:
$device->user_id
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?