如何在 CakePHP 3.0 中保存关联 Table
How to Save Associated Table in CakePHP 3.0
您好,我刚刚制作了一个功能,可以将数据保存在多个 table 中。
尽管,我按照中的说明进行操作
Instruction for Cakephp 3.0
它只保存一个数据table。
请看看我错过了什么。
谢谢
public function saveTest()
{
$goods = TableRegistry::get('Goods');
//$data = $this->request->data;
$data = [
'brand' => 'brand',
'name' => 'name',
'dis_price' => 100,
'w_price' => 90,
'line_des' => 'haha',
'line_w_des' => 'hehe',
'hash_tag' => 'hoho',
'price' => 100,
'good_stock' => [
'options' => 'asd',
'stock_count' => 100
]];
Debugger::log($data);
$entity = $goods->newEntity($data, [
'associated' => ['GoodsStocks']
]);
Debugger::log($goods->save($entity));
//Debugger::log('3');
}
public function initialize(array $config)
{
$this->entityClass('App\Model\Entity\Goods');
$this->table('goods');
$this->displayField('name');
$this->primaryKey('id');
$this->addBehavior('Timestamp');
$this->hasMany('GoodsStocks',[
'alias' => 'Users',
'foreignKey' => 'good_id',
'dependent' => true
]);
}
不幸的是它只保存了商品table中的数据。
谢谢
您的 GoodStock 关联数组应该是关联名称的下划线版本。另外,它可能不是一维数组,因此它是一个 hasMany 关联。您可以找到更多信息 here.
所以你的代码应该更像:
$data = [
'brand' => 'brand',
'name' => 'name',
'dis_price' => 100,
'w_price' => 90,
'line_des' => 'haha',
'line_w_des' => 'hehe',
'hash_tag' => 'hoho',
'price' => 100,
'good_stocks' => [
['options' => 'asd', 'stock_count' => 100]
]
];
希望你觉得有用。
PS:对于任何语法错误,我深表歉意,但英语不是我的母语;)
您好,我刚刚制作了一个功能,可以将数据保存在多个 table 中。 尽管,我按照中的说明进行操作 Instruction for Cakephp 3.0
它只保存一个数据table。
请看看我错过了什么。
谢谢
public function saveTest()
{
$goods = TableRegistry::get('Goods');
//$data = $this->request->data;
$data = [
'brand' => 'brand',
'name' => 'name',
'dis_price' => 100,
'w_price' => 90,
'line_des' => 'haha',
'line_w_des' => 'hehe',
'hash_tag' => 'hoho',
'price' => 100,
'good_stock' => [
'options' => 'asd',
'stock_count' => 100
]];
Debugger::log($data);
$entity = $goods->newEntity($data, [
'associated' => ['GoodsStocks']
]);
Debugger::log($goods->save($entity));
//Debugger::log('3');
}
public function initialize(array $config)
{
$this->entityClass('App\Model\Entity\Goods');
$this->table('goods');
$this->displayField('name');
$this->primaryKey('id');
$this->addBehavior('Timestamp');
$this->hasMany('GoodsStocks',[
'alias' => 'Users',
'foreignKey' => 'good_id',
'dependent' => true
]);
}
不幸的是它只保存了商品table中的数据。
谢谢
您的 GoodStock 关联数组应该是关联名称的下划线版本。另外,它可能不是一维数组,因此它是一个 hasMany 关联。您可以找到更多信息 here.
所以你的代码应该更像:
$data = [
'brand' => 'brand',
'name' => 'name',
'dis_price' => 100,
'w_price' => 90,
'line_des' => 'haha',
'line_w_des' => 'hehe',
'hash_tag' => 'hoho',
'price' => 100,
'good_stocks' => [
['options' => 'asd', 'stock_count' => 100]
]
];
希望你觉得有用。
PS:对于任何语法错误,我深表歉意,但英语不是我的母语;)