Yii2 Gridview 按权限过滤
Yii2 Gridview filter by permission
我有一个超级管理员,可以创建用户并可以为每个用户分配特定位置。这存储在一个简单的 table 中,我们在其中获取用户 ID 和位置 ID。
然后,我有 table 个客户。每个客户端还有一个位置,名为 loc_id。我如何进行过滤,以便在 Gridview 中,用户只能看到位于用户有权查看的位置的客户端(用户是一种管理员,可以在其管辖范围内操作客户端的数据)?
我通过
获取用户ID
$userId = \Yii::$app->user->identity->id
然后找到他可以查看的位置
$userLocation = Userlocations::find()-where(['user_id' => $userId])->all();
但是现在我如何将其应用于具有搜索模型和 DataProvider 的标准 Gridview,以便我仍然可以按其他属性对 GridView 进行过滤和排序?
$searchModel = new AsociatiiSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
首先在您的 AsociatiiSearch class 中,您需要添加一个 public 属性:
class AsociatiiSearch {
public $userLocation;
...
然后在您的控制器操作中找到 userLocation:
$userId = \Yii::$app->user->identity->id
$userLocation = Userlocations::find()-where(['user_id' => $userId])->all();
$searchModel = new AsociatiiSearch();
$searchModel->userLocation = $userLocation;
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
最后,在 AsociatiiSearch 搜索方法中,您可以使用全局 userLocation 添加另一个过滤器:
$query->andFilterWhere(['userLocation' => $this->userLocation]);
我有一个超级管理员,可以创建用户并可以为每个用户分配特定位置。这存储在一个简单的 table 中,我们在其中获取用户 ID 和位置 ID。
然后,我有 table 个客户。每个客户端还有一个位置,名为 loc_id。我如何进行过滤,以便在 Gridview 中,用户只能看到位于用户有权查看的位置的客户端(用户是一种管理员,可以在其管辖范围内操作客户端的数据)?
我通过
获取用户ID$userId = \Yii::$app->user->identity->id
然后找到他可以查看的位置
$userLocation = Userlocations::find()-where(['user_id' => $userId])->all();
但是现在我如何将其应用于具有搜索模型和 DataProvider 的标准 Gridview,以便我仍然可以按其他属性对 GridView 进行过滤和排序?
$searchModel = new AsociatiiSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
首先在您的 AsociatiiSearch class 中,您需要添加一个 public 属性:
class AsociatiiSearch {
public $userLocation;
...
然后在您的控制器操作中找到 userLocation:
$userId = \Yii::$app->user->identity->id
$userLocation = Userlocations::find()-where(['user_id' => $userId])->all();
$searchModel = new AsociatiiSearch();
$searchModel->userLocation = $userLocation;
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
最后,在 AsociatiiSearch 搜索方法中,您可以使用全局 userLocation 添加另一个过滤器:
$query->andFilterWhere(['userLocation' => $this->userLocation]);