我花了将近一整天的时间让一个belongsToMany保存在Cake v3中工作。我的代码如下:
列表belongsToMany PaymentTypes PaymentTypes belongsToMany Listings
表格
编目
class Listing extends Entity {
protected $_accessible = [
'*' => true,
'id' => false,
];
}
class ListingsTable extends Table {
public function initialize(array $config) {
$this->belongsToMany('PaymentTypes');
}
}
PaymentTypes
class PaymentType extends Entity {
protected $_accessible = [
'*' => true,
'id' => false
];
}
class PaymentTypesTable extends Table {
public function initialize(array $config) {
$this->belongsToMany('Listings');
}
}
列表控制器::添加
public function add() {
$listing=$this->Listings->newEntity();
if ($this->request->is('post')) {
$listing = $this->Listings->patchEntity($listing, $this->request->data);
if ($this->Listings->save($listing, ['associated' => ['ListingImages', 'PaymentTypes']])) {
$this->Flash->success('Your listing has been successfully submitted', ['key' => 'message']);
return $this->redirect(['action' => 'add']);
}
else{
debug($listing->errors());
$this->Flash->error('Please correct the errors below', ['key' => 'message']);
}
}
$this->set('paymentTypes', $this->Listings->PaymentTypes->find('list'));
}
请求数据
[
'title' => 'Test',
'description' => 'Some information',
'price' => '100.00',
'listing_type_id' => '1',
'vehicle_id' => '2',
'category_id' => '1',
'location' => 'Test',
'country_id' => '38',
'payment_types' => [
'_id' => [
(int) 0 => '1',
(int) 1 => '2',
(int) 2 => '3'
]
],
'listing_images' => [
(int) 0 => [
'name' => 'IMG-20160513-WA0014.jpg',
'type' => 'image/jpeg',
'tmp_name' => 'C:\Program Files\phpB619.tmp',
'error' => (int) 0,
'size' => (int) 87863
],
]
]
我使用了Cake书作为指南,我看不出有什么东西丢失,但是保存失败了。