我试图保存与实体B相关联的实体A,但到目前为止没有成功。
原因是当我试图在我的关系表中保存带有关联(实体B)的实体A时,实体B的id被设置但不是实体A的id。
另一种方式也是如此。
这是我的两个实体的代码:
实体A
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('name');
$this->primaryKey('user_id');
$this->addBehavior('Timestamp');
$this->belongsToMany('Shelves', [
'className' => 'Shelves',
'foreignKey' => 'shelf_id',
'targetForeignKey' => 'shelf_id',
'joinTable' => 'shelvesSalesmen',
'through' => 'ShelvesSalesmen'
]);
}
}
实体B
class ShelvesTable extends Table
{
/**
* Initialize method
*
* @param array $config The configuration for the Table.
* @return void
*/
public function initialize(array $config)
{
parent::initialize($config);
$this->table('shelves');
$this->displayField('shelf_id');
$this->primaryKey('shelf_id');
$this->addBehavior('Timestamp');
$this->belongsToMany('Salesmen', [
'className' => 'Users',
'foreignKey' => 'user_id',
'targetForeignKey' => 'user_id',
'joinTable' => 'shelves_salesmen',
'through' => 'ShelvesSalesmen'
]);
}
}
RelationShip表
class ShelvesSalesmenTable extends Table
{
/**
* Initialize method
*
* @param array $config The configuration for the Table.
* @return void
*/
public function initialize(array $config)
{
parent::initialize($config);
$this->table('shelves_salesmen');
$this->displayField('shelf_id');
$this->primaryKey(['shelf_id', 'user_id']);
$this->belongsTo('Shelves');
$this->belongsTo('Users');
}
}
并且保存与编辑和添加操作中的代码相同:
$user = $this->Users->patchEntity($user, $this->request->data);
$this->Users->save($user);
错误是:
无法插入行,缺少部分主键值。得到(1,),期待(shelf_id,user_id)
谢谢大家的时间。