我正在创建一个允许生成动态表单的工具。有几个表格有问题:
对于FieldValidation - 这实际上可能是来自Field的hasMany,但我不确定是否需要从Field表或连接表FieldValidation
设置此关系。 Validation
表只包含验证选项的定义。实际上 不需要来自FormField / Field表的belongsToMany
关系。如果简化了事情,hasMany
就可以了。
这甚至可能吗?
Form -> [FormField] -> Field -> [FieldValidation] -> Validation
我以前从未这样做过 - 所以如果有更好的方法来解决这个问题,我全都听见了。我主要担心的是能够选择Form
,包含Field's
,然后为所选的每个字段包含Validation
。显然,每个字段可以选择多个验证规则。
答案 0 :(得分:0)
有点晚了,但我确实解决了这个问题。
型号:UsersTable
class UsersTable extends Table
{
/**
* Initialize method
*
* @param array $config The configuration for the Table.
* @return void
*/
public function initialize(array $config)
{
parent::initialize($config);
$this->table('users');
$this->displayField('username');
$this->primaryKey('id');
$this->addBehavior('Timestamp');
$this->belongsToMany('Projects', [
'foreignKey' => 'user_id',
'targetForeignKey' => 'project_id',
'through' => 'ProjectsUsers'
]);
$this->hasMany('ProjectsUsers', [
'foreignKey' => 'user_id'
]);
}
}
型号:ProjectsTable
class ProjectsTable extends Table
{
/**
* Initialize method
*
* @param array $config The configuration for the Table.
* @return void
*/
public function initialize(array $config)
{
parent::initialize($config);
$this->table('projects');
$this->displayField('name');
$this->primaryKey('id');
$this->addBehavior('Timestamp');
$this->belongsToMany('Users', [
'foreignKey' => 'project_id',
'targetForeignKey' => 'user_id',
'through' => 'ProjectsUsers'
]);
$this->hasMany('ProjectsUsers', [
'foreignKey' => 'project_id'
]);
}
}
型号:ProjectsUsersTable - 这是JOIN表的模型(通过)
class ProjectsUsersTable extends Table
{
/**
* Initialize method
*
* @param array $config The configuration for the Table.
* @return void
*/
public function initialize(array $config)
{
parent::initialize($config);
$this->table('projects_users');
$this->displayField('id');
$this->primaryKey('id');
$this->addBehavior('Timestamp');
$this->belongsTo('Users', [
'foreignKey' => 'user_id'
]);
$this->belongsTo('Projects', [
'foreignKey' => 'project_id'
]);
$this->hasMany('ProjectsUsersPermissions', [
'foreignKey' => 'projects_users_id'
]);
}
}
型号:ProjectsUsersPermissions - 这是与联接表的关系
class ProjectsUsersPermissionsTable extends Table
{
/**
* Initialize method
*
* @param array $config The configuration for the Table.
* @return void
*/
public function initialize(array $config)
{
parent::initialize($config);
$this->table('projects_users_permissions');
$this->displayField('role');
$this->primaryKey('id');
$this->addBehavior('Timestamp');
$this->belongsTo('ProjectsUsers', [
'foreignKey' => 'projects_users_id'
]);
}
}
然后控制器找到行动
$this->Projects->find()
->where(
[
'Projects.id' => $projectId
]
)
->contain(
[
'Users', // through belongsToMany
'ProjectsUsers' => [ // through hasMany [joinTableModel]
'ProjectsUsersPermissions' // through hasMany
]
]
)
->first();
对于这种情况,这可能有点过头了,而且这不是我的确切实现 - 所以不要以为我只是做了不必要的连接/包含。在我的现实生活场景中,这非常有效。
希望这有助于某人!