当我试图坚持它时关联belongsToMany时出错

时间:2016-03-06 06:21:47

标签: cakephp cakephp-3.0 has-and-belongs-to-many

当我尝试通过表'media_products'将模型'Media'与模型'Product'关联在'many to many'关系中时。一旦它直接插入到'media_products'表上,我就可以拯救通过类'ProductsTable'的方法'get'和'find'关联的所有值,但我不能使用'ProductsTable'类的'save'方法来保存这些值。 哪个是正确的方法来坚持与之相关的相关模型? 而我正在使用CakePHP的3.X版本 使用它来代码。

/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']);
}

这样表'media_products'没有被填充,我已经尝试了很多方法来做到这一点,例如,以下内容: '$ products-> media ['._ id'] = array($ media_id)'

0 个答案:

没有答案