Cakephp 尝试保持关联时,关联属性出错
当我试图通过“媒体产品”表将“多对多”关系中的“媒体”模型与“产品”模型相关联时。一旦直接将“ProductsTable”类的“get”和“find”方法插入到表“media_products”中,我就可以解救所有通过该类的“get”和“find”方法关联的值,但我不能使用“ProductsTable”类的“save”方法来持久化这些值。 哪一种被认为是正确的方法来持久化与之相关的模型? 而我使用的是CakePHP的3.X版本 遵循上面使用的代码 /src/Model/Table/ProductsTable.phpCakephp 尝试保持关联时,关联属性出错,cakephp,cakephp-3.0,has-and-belongs-to-many,Cakephp,Cakephp 3.0,Has And Belongs To Many,当我试图通过“媒体产品”表将“多对多”关系中的“媒体”模型与“产品”模型相关联时。一旦直接将“ProductsTable”类的“get”和“find”方法插入到表“media_products”中,我就可以解救所有通过该类的“get”和“find”方法关联的值,但我不能使用“ProductsTable”类的“save”方法来持久化这些值。 哪一种被认为是正确的方法来持久化与之相关的模型? 而我使用的是CakePHP的3.X版本 遵循上面使用的代码 /src/Model/Table/Product
class ProductsTable extends Table
{
public function initialize(array $config)
{
parent::initialize($config);
$this->table('products');
$this->displayField('id');
$this->primaryKey('id');
$this->addBehavior('Timestamp');
$this->belongsToMany('Media', [
'joinTable' => 'media_products',
'className' => 'Categories',
'propertyName' => 'media',
'dependent' => true,
'saveStrategy' => 'replace'//'append'
]);
}
/src/Model/Table/MediaTable.php
class MediaTable extends Table
{
public function initialize(array $config)
{
parent::initialize($config);
$this->table('media');
$this->displayField('name');
$this->primaryKey('id');
$this->addBehavior('Timestamp');
$this->belongsToMany('Products', [
'foreignKey' => 'media_id',
'targetForeignKey' => 'product_id',
'joinTable' => 'media_products'
]);
}
/src/Controller/ProductsController.php
class ProductsController extends AppController
{
public function gallery($id = null){
//if($id == null){$id = $this->request->pass['id'];}
print($id);
$product = $this->Products->find('all',['conditions'=>['Product_id ' => $id],
'contain' => ['MainImages'] ])->first();
if($this->request->is(['patch', 'post', 'put'])){
// this method upload the file, persist and return the media object related
$media = $this->Media->update_and_save($this->request->data['media_upload']
, $this->request->data['media']
, 'gallery');
array_push($product->media,$media);
if($this->Products->save($product)){
$this->Flash->success(__('Arquivo de media adcionado com sucesso.'));
return $this->redirect(['action' => 'gallery']);
}
$this->Flash->error(__('Falha ao salvar o arquivo de media.'));
}
$this->set('product', $product);
$this->set('_serialize', ['products']);
}
通过这种方式不填充“media_products”表,我尝试了多种方法,例如:
“$products->media[”.\u id']=array($media\u id)欢迎使用SO!英语网站也是如此。你能翻译一下你的问题吗?或者把问题贴在为什么你要使用媒体协会的
'className'=>'Categories'
中?这是在网站的另一个功能中使用的,我会去掉它以避免出错