Take two.
in Device.php:
// creates a users property within a Device, a container of associated Users
public function relations()
{
return array(
'users'=>array(self::MANY_MANY, 'User', // don't use HAS_MANY
'user_devices(user_id, device_id)'), // composite key assumed
);
}
then to find if the requested device is owned by the requesting user:
$device = Device::model()->findByPk($deviceId);
if ( $device->users->findByPk($userId) == Null )
$device = Null;
It seems like this would work but inefficiently retrieve a lot of unneeded User records, since you already know who the user is and likely already have their activeRecord. To avoid this innefficiency, the Yii Agile Development book uses raw SQL for M2M relationship queries within the parent model (Device.php):
// "Agile" uses a $user AR argument, you can use $userId instead
public function doesUserOwnDevice($userId)
{
$sql = "SELECT user_id FROM user_devices WHERE
device_id=:deviceId AND user_id=:userId";
$command = Yii::app()->db->createCommand($sql);
$command->bindValue(":deviceId", $this->id, PDO::PARAM_INT);
$command->bindValue(":userId", $userId, PDO::PARAM_INT);
return $command->execute()==1 ? true : false;
}
I used Device
rather than Devices
for the name of the model (likewise device
for the name of the table). Refactor if you cut and paste. Likewise for User
. Likewise for missing "tbl_" prefix.