Issues adding multiple rows into table

Hello!

First of all I’m glad there is a forum where I can ask questions since I’ve been desperately searching for answers but can’t quite get it right.

I’m building a webapp with cakephp and one of my add functions should insert data into one table while adding data into another linked to the original insertion.

It’s for vehicle checklists, it adds one row on a table with the current user_id, vehicle_id and date while adding onto another table all of the items_id with a 1 or 0 on a checked field. (pictures to illustrate)

It’s not inserting the multiple lines on the second table :frowning:

I’ve tried SaveMany-> as well, that gives an error.

    public function add()
{
    $checklist = $this->Checklists->newEmptyEntity();
    $checkrelatorios = $this->Checklists->Checkrelatorios->newEmptyEntity();
    
    debug($this->request->getData());
    
    if ($this->request->getData('veiculo_id') && $this->request->getData('user_id') == null){
        
        $items = $this->Checklists->Checkrelatorios->Items->find('all', array('conditions' => array('Items.veiculo_id' => $this->request->getData('veiculo_id')), 'order' => array('Items.compartment_id' => 'ASC')));//debug($items);die;
        $compartments = $this->Checklists->Checkrelatorios->Items->Compartments->find('list');
        $comps = $compartments->toArray();
        $this->set(compact('comps', 'compartments', 'items'));
        
    
        
    }else if ($this->request->getData('user_id')){//debug($checklist);die;
        
        if ($this->request->is('post')) {//debug($this->request->getData());
            
            $checklist = $this->Checklists->patchEntity($checklist, $this->request->getData());
            //$checkrelatorios = $this->Checklists->Checkrelatorios->newEntities($this->request->getData('checkrelatorio'));
            //debug($checklist);die;
        if ($this->Checklists->Checkrelatorios->Save($checklist)) {//debug($checklist);die;
            //$this->Checklists->Checkrelatorios->SaveMany($checkrelatorios);
            $this->Flash->success(__('The checklist has been saved.'));

            return $this->redirect(['action' => 'index']);
        }
            $this->Flash->error(__('The checklist could not be saved. Please, try again.'));debug($checklist);
        }
    }
    
    $user = $this->Auth->user('id');
    $veiculos = $this->Checklists->Veiculos->find('list', ['limit' => 200]);
    $veicEsc = $veiculos->toArray();
    
    
    $this->set(compact('checklist', 'veicEsc', 'user', 'veiculos'));
}

image

$checklist is not a Checkrelatorio, it’s a Checklist, which should have all the Checkrelatorios in it. This line should be

if ($this->Checklists->save($checklist))

This should save both the checklist and the relations all at once, with the checklist ID being added to each relation. If that doesn’t save the relations, debug the $checklist both before and after trying to save and see what it looks like.

Thank you for your reply!

I fixed it as you said, not it writes on the table but not on the relation.

Here’s the debug BEFORE save:

 APP/Controller/ChecklistsController.php (line 83)
object(App\Model\Entity\Checklist) id:0 {
'user_id' => (int) 36'veiculo_id' => (int) 2'[new]' => true'[accessible]' => [
'user_id' => true,'veiculo_id' => true,'created' => true,'user' => true,'veiculo' => true,'item' => true,'checkrelatorio' => true,
]'[dirty]' => [
'user_id' => true,'veiculo_id' => true,
]'[original]' => []'[virtual]' => []'[hasErrors]' => false'[errors]' => []'[invalid]' => []'[repository]' => 'Checklists'protected _accessible => [
'user_id' => true,'veiculo_id' => true,'created' => true,'user' => true,'veiculo' => true,'item' => true,'checkrelatorio' => true,
]protected _fields => [
'user_id' => (int) 36,'veiculo_id' => (int) 2,
]protected _original => []protected _hidden => []protected _virtual => []protected _dirty => [
'user_id' => true,'veiculo_id' => true,
]protected _accessors => [
'App\Model\Entity\Checklist' => [
'get' => [
'user_id' => '','veiculo_id' => '','checkrelatorios' => '',
],'set' => [
'user_id' => '','veiculo_id' => '',
],
],'App\Model\Entity\Checkrelatorio' => [
'set' => [
'items_id' => '','checked' => '',
],
],
]protected _new => trueprotected _errors => []protected _invalid => []protected _registryAlias => 'Checklists'
}

And AFTER save:

**APP/Controller/ChecklistsController.php** (line **84** )

object(App\Model\Entity\Checklist) id:0 {'user_id' => (int) 36'veiculo_id' => (int) 2'created' => object(Cake\I18n\FrozenTime) id:1 {}'id' => (int) 37'[new]' => false'[accessible]' => ['user_id' => true,'veiculo_id' => true,'created' => true,'user' => true,'veiculo' => true,'item' => true,'checkrelatorio' => true,]'[dirty]' => []'[original]' => []'[virtual]' => []'[hasErrors]' => false'[errors]' => []'[invalid]' => []'[repository]' => 'Checklists'protected _accessible => ['user_id' => true,'veiculo_id' => true,'created' => true,'user' => true,'veiculo' => true,'item' => true,'checkrelatorio' => true,]protected _fields => ['user_id' => (int) 36,'veiculo_id' => (int) 2,'created' => object(Cake\I18n\FrozenTime) [id: 1](http://192.168.1.99/checklists/add#cake-db-object-5f42df103ea7a7.46751758-1) {},'id' => (int) 37,]protected _original => []protected _hidden => []protected _virtual => []protected _dirty => []protected _accessors => ['App\Model\Entity\Checklist' => ['get' => ['user_id' => '','veiculo_id' => '','checkrelatorios' => '','id' => '','created' => '',],'set' => ['user_id' => '','veiculo_id' => '','created' => '','id' => '',],],'App\Model\Entity\Checkrelatorio' => ['set' => ['items_id' => '','checked' => '',],],]protected _new => falseprotected _errors => []protected _invalid => []protected _registryAlias => 'Checklists'}

It’s super hard to make sense of that. Any chance of better formatting?

My best guess is that where you have 'checkrelatorio' => true in the accessible array of the Checklist entity, it needs to be 'checkrelatorios' => true. There should be a checkrelatorios property in the entity with a list of those entities in it, but that’s entirely missing, and lack of accessibility seems the most likely culprit.

Hello again, and thank you for trying to help me!

I edited the Checklist entity as you suggested but it still won’t write anything on the Checkrelatorios table.

I should add that this should be saving multiple rows into the associated table, and I am saying this because the only way I got this to work before when I was only using one table was with the SaveMany method but that’s not working here either now, and I’m not sure how to apply it to two tables anyways…

Do you have a discord account or something where I can show you the project in a easier way?

better view of the AFTER debug

(open image in new tab, I wasn’t able to copy paste the debug with format :frowning: )

Putting ``` on a line by itself before and after code that you want to retain formatting should work. You should get familiar with how to do this in general; it makes it easier for people to help you. (Many won’t click a link to go view an image on another site, and what’s here is too small for me to read.)

Can you share the code from your ChecklistsTable where you define the association to Checkrelatorios?

public function initialize(array $config): void
    {
        parent::initialize($config);

        $this->setTable('checklists');
        $this->setDisplayField('id');
        $this->setPrimaryKey('id');

        $this->addBehavior('Timestamp');

        $this->belongsTo('Users', [
            'foreignKey' => 'user_id',
        ]);
        $this->belongsTo('Veiculos', [
            'foreignKey' => 'veiculo_id',
            'joinType' => 'INNER',
        ]);
        $this->hasMany('Checkrelatorios', [
            'foreignKey' => 'checklist_id',
        ]);
    }

So, given the hasMany relation you’ve got defined, and the data you’ve shown, and the accessibility, this line:

$checklist = $this->Checklists->patchEntity($checklist, $this->request->getData());

should create a checkrelatorios property in the $checklist. That’s not happening for you. I’m wondering if somehow $this->Checklists is a generic Cake table instead of your specific one. Can you try

debug(get_class($this->Checklists));
**APP/Controller/ChecklistsController.php** (line **63** )

'App\Model\Table\ChecklistsTable'

Well then, I’m stumped. Hopefully, with the information added, someone else will be able to spot what I’m missing.