这可能有点奇怪,但我会尽力解释一下。基本上我有一个包含用户的表和一个包含客户的表。用户有权仅查看某些客户的数据。所以我想我应该为用户权限创建一个单独的表,将用户 ID 和客户 ID 作为外键,并且每个客户/用户权限占一行。
当管理员使用名为 UserForm 的类(下面简称为引用)(它使用 Zend\Form)向数据库添加新用户时,我还想将表单旁边的所有客户显示为可以选择的按钮添加为权限。现在,我想我可以通过一个 JavaScript 数组来实现这一点,该数组在选择/取消选择时附加或删除客户 ID,然后将该数组作为隐藏值传递到表单,最后循环遍历该数组,将一行插入到数组中每个客户 ID 的权限表,并获取已创建的用户 ID。我不确定这是否是最好的方法,但这是我能想到的最好的方法。
希望这至少可以稍微理解一点。所以,我有一种形式,但我想插入到两个不同的表中。我想我的问题是如何将数组作为值传递给表单?当调用 saveUser() 方法时,如何不仅插入用户表,而且插入权限表(我也会在下面发布)。另外,这是一种非常奇怪的做法,让我感到不必要的困难吗?我很想听听是否有更简单的方法。
我的用户窗体类:
namespace Admin\Form;
use Zend\Form\Form;
class UserForm extends Form
{
public function __construct($name = null)
{
parent::__construct('user');
$this->setAttribute('method', 'post');
$this->add(array(
'name' => 'userId',
'attributes' => array(
'type' => 'Hidden',
),
));
$this->add(array(
'name' => 'activated',
'attributes' => array(
'value' => 1,
'type' => 'Hidden',
),
));
$this->add(array(
'name' => 'username',
'attributes' => array(
'type' => 'text',
),
'options' => array(
'label' => 'Username:',
),
));
$this->add(array(
'name' => 'firstname',
'attributes' => array(
'type' => 'text',
),
'options' => array(
'label' => 'First name:',
),
));
$this->add(array(
'name' => 'lastname',
'attributes' => array(
'type' => 'text',
),
'options' => array(
'label' => 'Last name:',
),
));
$this->add(array(
'name' => 'submit',
'attributes' => array(
'type' => 'submit',
'value' => 'Go',
'id' => 'submitbutton',
),
));
}
}
我的 saveUser() 方法
public function saveUser(User $user)
{
$data = array(
'firstname' => $user->firstname,
'lastname' => $user->lastname,
'username' => $user->username,
'activated' => $user->activated,
);
$userId = (int)$user->userId;
if ($userId == 0) {
$this->tableGateway->insert($data);
} else {
if ($this->getUser($userId)) {
$this->tableGateway->update($data, array('userId' => $userId));
} else {
throw new \Exception('User ID does not exist');
}
}
}
最佳答案
一种方法是使用表单字段集。一个表单可以有多个Fieldset,每个Fieldset可以绑定(bind)到不同的实体。
当实体之间存在一对一关系时,这些非常有用
然后,您将创建 teo 实体,例如用户实体(您已经拥有)和一个代表您的权限的新实体。
您将为每个对象创建一个 Fieldset,并将对象绑定(bind)到字段集。 (例如UserFieldSet和PermissionFieldset)
查看有关表单字段集的部分:
http://zf2.readthedocs.org/en/latest/modules/zend.form.advanced-use-of-forms.html
如果您有一对多关系,即。一个用户可以拥有许多权限,那么您最好查看表单集合:
http://zf2.readthedocs.org/en/latest/modules/zend.form.collections.html
还有一个为一对多关系动态添加新行的示例。
关于php - 想要在ZF2中使用一种形式插入两个表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16212527/