对具有许多客户端和具有许多用户的客户端的用户使用许多关系查询。尝试查看特定用户的特定客户端的记录。如果该客户端未与该用户关联,则重定向到其他页面。
// the relation in the client model
public function relations()
{
// NOTE: you may need to adjust the relation name and the related
// class name for the relations automatically generated below.
return array(
'owners'=>array(self::MANY_MANY, 'User','owner_client(owner_id, client_id)'),
);
}
//the relation in the user model
public function relations()
{
return array(
'clients'=>array(self::MANY_MANY, 'Clients','owner_client(owner_id, client_id)'),
);
}
//determine if user can view this client
//client record
$client_record = Clients::model()->findByPk($id);
//many query to find users
$users = $client_record->owners;
//if user id is not found in array, redirect
if (!in_array(Yii::app()->user->id, $users))
{
$this->redirect(array('/site/dashboard'));
}
上述代码重定向,即使我知道客户端与登录的用户相关
答案 0 :(得分:1)
当您致电$users = $client_record->owners;
时,您所获得的是与当前客户关联的所有用户模型的数组。因此,您将整数与对象进行比较,这意味着您的in_array()条件将始终失败。
我建议您构建条件查询以进行验证检查。这样的事情应该有效:
$model = Clients::model()->with(
array(
'owners'=>array(
'select'=>'owner_id',
'condition'=>'user.id = '.Yii::app()->user->id,
),
)
)->findByPk($id);
if ($model === null) {
$this->redirect(array('/site/dashboard'));
}