来自$this->request-data
的数据需要修改,因此我不能直接使用表单来填充所有表。在添加列" state"。
order_id int(11) PK
part_id int(11) PK
state varchar(10)
我从$this->request-data
获取ID并相应地修改它:
$this->request->data['parts']['_ids'][]=....
其余的按照手册进行:
$order = $this->Orders->newEntity();
$this->Orders->patchEntity($order, $this->request->data);
$this->Orders->save($order);
我无法修改传入数据以将其保存到状态列
编辑:
"州"字段仍为空值。OrdersTable中
public function initialize(array $config)
{
parent::initialize($config);
$this->table('orders');
$this->displayField('id');
$this->primaryKey('id');
$this->addBehavior('Timestamp');
$this->belongsTo('Users', [
'foreignKey' => 'user_id',
'joinType' => 'INNER',
]);
$this->belongsToMany('Parts', [
'foreignKey' => 'order_id',
'targetForeignKey' => 'part_id',
'joinTable' => 'orders_parts',
'through' => 'OrdersParts',
]);
$this->belongsToMany('Sets', [
'foreignKey' => 'order_id',
'targetForeignKey' => 'set_id',
'joinTable' => 'orders_sets',
]);
}
OrdersTable中
public function initialize(array $config)
{
parent::initialize($config);
$this->table('parts');
$this->displayField('name');
$this->primaryKey('id');
$this->addBehavior('Timestamp');
$this->belongsTo('Orders', [
'foreignKey' => 'order_id',
'joinType' => 'INNER',
]);
$this->belongsToMany('Orders', [
'foreignKey' => 'part_id',
'targetForeignKey' => 'order_id',
'joinTable' => 'orders_parts',
]);
$this->belongsToMany('States', [
'foreignKey' => 'part_id',
'targetForeignKey' => 'state_id',
'joinTable' => 'parts_states'
]);
}
插入
$order = $this->Orders->newEntity();
$order->status = 'new';
$order->user_id = $this->Auth->user('id');
$this->request->data['parts'][0]['_joinData']['state'] = "whatever";
$this->Orders->patchEntity(
$order,
$this->request->data,
['associated' => ['Sets','Parts._joinData']]
);
$this->Orders->save(
$order,
['associated' => ['Sets','Parts._joinData']]
);
我必须将aslo SetsModel包含在关联的中。
答案 0 :(得分:7)
$ this-> request-> data ['parts'] ['_ ids']允许您连接表但不能以这种方式添加数据。 为此,您的$ this-> request-> data ['parts']结构必须如下所示:
'parts' => [
0 => [
'id'=> 1,
'_joinData' => [
'state' => 'exampleSate'
]
]
]
确保您的'parts'数组中不再包含'_ids'数组,否则您将无法将数据保存到连接表中。
'id'字段对应于相关部分的id。设置它:
$this->request->data['parts'][0]['id'] = <idOfTheConcernedPart>;
要设置“州”字段,请执行以下操作:
$this->request->data['parts'][0]['_joinData']['state'] = "whatever";
最后你需要通过向patchEntity添加一些配置并保存方法来告诉cakephp你正在保存一些_joinData:
$this->Orders->patchEntity(
$order,
$this->request->data,
['associated' => ['Parts._joinData']]
);
$this->Orders->save(
$order,
['associated' => ['Parts._joinData']]
);
我希望它有所帮助,
欢呼声。