When I tried to associate the model 'Media' with model 'Product' in a relationship 'many to many' through table 'media_products'. I can rescue all values associated through methods 'get' and 'find' of class 'ProductsTable' once It was directly inserted on table 'media_products', but I can't persist this values using the method 'save' of class 'ProductsTable'. Which is suposed to be the correctly way to persist the related models associated to It? Whereas I'm using the 3.X version of CakePHP Folloing the codes using on that.
/src/Model/Table/ProductsTable.php
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']);
}
This way the table 'media_products' isn't being populated , I have tried many ways to do that, for example, the following: '$products->media['._id'] = array($media_id)'