Cakephp - 1~n ratio

Asked

Viewed 133 times

1

Good evening, I’m having a hard time on Cakephp 3 and the problem is this::

Cannot Insert Row, some of the Primary key values are Missing. Got (, ), expecting (idstorie, users_iduser)

  • The system should add a "Storie" to the BD, in which it should automatically generate its ID (Auto_implement) and take the ID of the user who is logged in.

TEMPLATE/STORIES/ADD

<nav class="large-3 medium-4 columns" id="actions-sidebar">
    <ul class="side-nav">
        <li class="heading"><?= __('Actions') ?></li>
        <li><?= $this->Html->link(__('List Stories'), ['action' => 'index']) ?></li>
    </ul>
</nav>
<div class="stories form large-9 medium-8 columns content">
    <?= $this->Form->create($story) ?>
    <fieldset>
        <legend><?= __('Add Story') ?></legend>
        <?php
            echo $this->Form->input('title');
            echo $this->Form->input('content');
            echo $this->Form->input('users_iduser',['value'=>$authUser['iduser'],'type'=>'hidden']); //essa linha pega o usuário da sessão que carrega ao logar.
        ?>
    </fieldset>
    <?= $this->Form->button(__('Submit')) ?>
    <?= $this->Form->end() ?>
</div>

CONTROLLER/STORIESCONTROLLER

public function add()
    {
        $story = $this->Stories->newEntity();
        if ($this->request->is('post')) {
            $this->Stories->patchEntity($story, $this->request->data);
            if ($this->Stories->save($story)) {
                $this->Flash->success(__('The story has been saved.'));
                return $this->redirect(['action' => 'index']);
            } else {
                $this->Flash->error(__('The story could not be saved. Please, try again.'));
            }
        }
        $this->set(compact('story'));
        $this->set('_serialize', ['story']);
    }

TABLE/STORIESTABLE

namespace App\Model\Table;

use Cake\ORM\Query;
use Cake\ORM\RulesChecker;
use Cake\ORM\Table;
use Cake\Validation\Validator;

class StoriesTable extends Table
{

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

        $this->table('stories');
        $this->displayField('title');
        $this->primaryKey(['idstorie', 'users_iduser']);

        $this->addBehavior('Timestamp');
    }

    public function validationDefault(Validator $validator)
    {
        $validator
            ->integer('idstorie')
            ->allowEmpty('idstorie', 'create');

        $validator
            ->requirePresence('title', 'create')
            ->notEmpty('title');

        $validator
            ->requirePresence('content', 'create')
            ->notEmpty('content');

        $validator
            ->integer('users_iduser')
            ->allowEmpty('users_iduser', 'create');

        return $validator;
    }
}

ENTITY/STORY

namespace App\Model\Entity;

use Cake\ORM\Entity;

class Story extends Entity
{

    public $belongsTo = array('User'); 

    protected $_accessible = [
        '*' => true,
        'idstorie' => false,
        'users_iduser' => false
    ];
}

Thanks in advance.

2 answers

1


[RESOLVED] - I redid the entire database from scratch.

The mistake was: Cannot Insert Row, some of the Primary key values are Missing. Got (, ), expecting (idstorie, users_iduser)

The problem was because I managed the database with the Mysql Workbench based on my design, and the settings were conflicting with the BAKE(Code generator from Cakephp).

  • Tip for those starting with CAKE:

Do it all by hand, don’t rely on tools, so you’ll know exactly where the bug is, and you won’t go through the same trouble I did. I lost almost 2 days with this mistake.

0

If someone comes across this type of error, in a Manytomany relation, make explicit which foreign keys of the Table in the Table Classes. For example (in a Manytomany relation between User and Alert Tables (without using cake plural convention)):

class AlertaTable extends Table
{
    public function initialize(array $config)
    {
        $this->belongsToMany('Usuario', [
                                         'joinTable' => 'alerta_usuario', 
                                         'foreignKey' => 'alerta_id'
                                        ]
                            );
    }
}

And in the User Class:

class UsuarioTable extends Table
    {
        public function initialize(array $config)
        {
            $this->belongsToMany('Alerta', [
                                        'joinTable' => 'alerta_usuario', '
                                        foreignKey' => 'usuario_id'
                                        ]
                            );
        }
    }

This should solve the problem. Remembering that it is not necessary to create the Table Class for the link table, Cake solves this for you.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.