Search code examples
cakephphas-manymodel-associationscakephp-3.2

multiple select for hasMany association in CakePHP 3


I have two tables seller_businesses and seller_business_categories. and their association is as follows

SellerBusinessesTable.php

    $this->hasMany('SellerBusinessCategories', [
        'foreignKey' => 'seller_business_id'
    ]);

SellerBusinessCategories.php

$this->belongsTo('SellerBusinesses', [
    'foreignKey' => 'seller_business_id',
    'joinType' => 'INNER'
]);

I'm using a single form to save data in both tables

<?= $this->Form->create($sellerBusiness, ['type' => 'file']) ?>
<?= $this->Form->input('company_name') ?>
<?= $this->Form->input('proof', ['type' => 'file']) ?>
<?= $this->Form->input('seller_business_categories._category_ids', ['multiple' => true, 'options' => $categories]) ?>
<?= $this->Form->button('submit', ['type' => 'submit']) ?>
<?= $this->Form->end() ?>

And controller action is

$sellerBusiness = $this->SellerBusinesses->newEntity();
if ($this->request->is('post')) {
  $sellerBusiness->seller_id = $this->Auth->user('id');
  $sellerBusiness = $this->SellerBusinesses->patchEntity($sellerBusiness, $this->request->data, [
   'associated' => [
      'SellerBusinessCategories'
   ]
 ]);
 debug($sellerBusiness);
 if ($save_s_b = $this->SellerBusinesses->save($sellerBusiness)) {
    debug($save_s_b);
    $this->Flash->success(__('The seller business has been saved.'));

    return $this->redirect(['controller' => 'SellerBusinesses', 'action' => 'view', $save_s_b->id]);
  } else {
    $this->Flash->error(__('The seller business could not be saved. Please, try again.'));
  }
}

But this is not saving record to seller_business_categories table.

From document Here

// Multiple select element for belongsToMany
echo $this->Form->input('tags._ids', [
    'type' => 'select',
    'multiple' => true,
    'options' => $tagList,
]);

But this is not working. Is there any other way for hasMany

debug($this->request->data); gives

'seller_business_categories' => [
        '_category_ids' => [
            (int) 0 => '1',
            (int) 1 => '2'
        ]
    ],

and debug($sellerBusiness); after patchEntity

object(App\Model\Entity\SellerBusiness) {

    'seller_id' => (int) 16,
    'company_name' => 'My company',
    'seller_business_categories' => [
        (int) 0 => object(App\Model\Entity\SellerBusinessCategory) {

            (int) 0 => '1',
            (int) 1 => '2',
            '[new]' => true,
            '[accessible]' => [
                '*' => true
            ],
            '[dirty]' => [
                (int) 0 => true,
                (int) 1 => true
            ],
            '[original]' => [],
            '[virtual]' => [],
            '[errors]' => [],
            '[invalid]' => [],
            '[repository]' => 'SellerBusinessCategories'

        }
    ],
    '[new]' => true,
    '[accessible]' => [
        '*' => true,
    ],
    '[dirty]' => [
        'seller_id' => true,
        'company_name' => true,
        'seller_business_categories' => true,
    ],
    '[original]' => [],
    '[virtual]' => [],
    '[errors]' => [],
    '[invalid]' => [],
    '[repository]' => 'SellerBusinesses'

}

and error

Error: SQLSTATE[HY000]: 
General error: 1364 Field 'category_id' doesn't have a default value in seller_business_categories table

Solution

  • SellerBusinessesTable

    $this->belongsToMany('Categories');
    

    CategoriesTable

    $this->belongsToMany('SellerBusinesses', [
        'foreignKey' => 'category_id',
        'targetForeignKey' => 'seller_business_id',
        'joinTable' => 'categories_seller_businesses'
    ]);
    

    // Pivot tables must be sorted alphabetically

    bin/cake bake migration CreateCategoriesSellerBusinesses seller_business_id:integer category_id:integer created modified
    

    CategoriesSellerBusinessesTable

    $this->belongsTo('SellerBusinesses', [
        'foreignKey' => 'seller_business_id',
        'joinType' => 'INNER'
    ]);
    
    $this->belongsTo('Categories', [
        'foreignKey' => 'category_id',
        'joinType' => 'INNER'
    ]);
    

    Add.ctp

    <?= $this->Form->create($sellerBusiness, ['type' => 'file']) ?>
        ...
        <?= $this->Form->input('categories', ['type' => 'select', 'options' => $categories, 'multiple' => 'select', 'label' => __('Categories')]) ?>
        ...
    <?= $this->Form->end() ?>
    

    SellerBusinessesController

    public function add()
    {
        $sellerBusiness = $this->SellerBusinesses->newEntity();
    
        if ($this->request->is('post')) {
    
            $sellerBusiness = $this->SellerBusinesses->patchEntity($sellerBusiness, $this->request->data);
    
            $sellerBusiness->seller_id = $this->Auth->user('id');
    
            if(isset($this->request->data['categories'])) 
            {
                $sellerBusiness -> categories = $this->SellerBusinesses->Categories->find()->where(['id IN' => $this->request->data['categories']])->all()->toArray();
            } 
    
            if ($this->SellerBusinesses->save($sellerBusiness)) {
    
                $this->Flash->success(__('The sellerBusiness has been saved.'));
    
                return $this->redirect(['action' => 'index']);
    
            } else {
    
                $this->Flash->error(__('The seller could not be saved. Please, try again.'));
    
            }
        }
    
        $categories = $this -> SellerBusinesses-> Categories-> find('treeList');  
    
        $this->set(compact('sellerBusiness', 'categories'));
        $this->set('_serialize', ['sellerBusiness']);