我们正在尝试以用户只能检索与其帐户相关的数据的方式设置REST API。到目前为止,我们只有一个公共API,所有这些都像个魅力一样。公共API仍然会被使用,因此我们从头开始。
我们有一个User
模型,可以扩展ActiveRecord
和实现IdentityInterface
。用户将与Customer
模型有关系(许多:许多,但至少一个)。用户将拥有only one MASTER
客户。以上内容使用3个表保存在数据库中app_customer_users
,app_customers
并且link_customer_users_customers
。连接表包含一个布尔字段master
。
在用户模型中:
public function getCustomers() {
return $this->hasMany(Customer::className(), ['id' => 'customer_id'])
->viaTable('link_customer_users_customers', ['user_id' => 'id']);
}
在客户模型中:
public function getUsers() {
return $this->hasMany(User::className(), ['id' => 'user_id'])
->viaTable('link_customer_users_customers', ['customer_id' => 'id']);
}
如果我们要求所有客户,这将非常有用,他们将被填充“用户”(如果我们将其添加到extraFields
等等,等等...)
新的API用于Basic user:pass
身份验证,我们可以通过调用获取当前的用户对象/身份Yii::$app->user->getIdentity()
。
当用户以一种可以通过调用Yii::$app->user->getIdentity()->customer_id
OR获得的方式进行连接时,我们希望能够包含客户ID Yii::$app->user->getIdentity()->getCustomerId()
。客户ID应该是联接master
表中的ID == true
。
我们尝试将其添加到中fields
,就像我们以前处理hasOne
关系时一样,但是在这种情况下,它似乎不起作用:
$fields['customer_id'] = function($model) {
return $model->getCustomers()->where('link_customer_users_customers.master', true)->one()->customer_id;
}; // probably the where part is our porblem?
我们尝试过创建这样的自定义getter:
public function getCustomerId() {
return $this->getCustomers()->andFilterWhere(['link_customer_users_customers.master' => true])->one()->customer_id;
}
最后一次尝试导致错误:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'link_customer_users_customers.master' in 'where clause'\nThe SQL being executed was: SELECT * FROM `app_customers` WHERE (`link_customer_users_customers`.`master`=TRUE) AND (`id`='93')
我们一直在文档中和Google上进行搜索,但没有找到有关如何执行此操作的示例。
根据接受的答案,我们添加了一些代码。
在User
模型中:
// Include customer always with user
public static function findIdentity($id) {
return static::findOne($id)->with('customer');
}
// Next to `getCustomers()`, added this `hasOne` relation to get only the customer from
// which the current user is the master user
public function getCustomer() {
return $this->hasOne(Customer::className(), ['id' => 'customer_id'])
->viaTable('link_customer_users_customers', ['user_id' => 'id'], function ($query) {
$query->andWhere(['master' => 1]);
});
}
// Getter, just because
public function getCustomerId() {
return $this->customer->id;
}
现在,我们可以通过在项目中调用Yii::$app->user->getIdentity()->customer->id
ORYii::$app->user->identity->customer->id
等来从客户那里获取ID 。
您应该添加如下所示的关系,并将anonymous
函数用作第三个参数,viaTable
以添加另一个条件以将master
字段检查为true。
public function getMasterCustomerId() {
return $this->hasOne(Customer::className(), ['id' => 'customer_id'])
->viaTable('link_customer_users_customers', ['user_id' => 'id'],function($query){
$query->andWhere(['master' => 1]);
});
}
然后可以将其用于登录用户,如下所示。
Yii::$app->user->identity->masterCustomerId->id;
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句