Cakephp 3 Базовая таблица или представление не найдено, таблица не множественная - PullRequest
0 голосов
/ 19 марта 2019

Привет, поэтому я создал таблицу с именем health_records, запекла модель и создал сущность с именем HealthRecord.php и таблицу HealthRecordsTables.php. Пытался сохранить данные к нему, и он выкинул мне эту ошибку

SQLSTATE[42S02]: Base table or view not found: 1146 Table 'sparkplug.health_record' doesn't exist

Ниже приведен код, который у меня есть для соответствующих файлов

Контроллер

 public function test() {
    $this->loadModel('HealthRecord');

    $HealthRecord =$this->HealthRecord->newEntity();

    $data = [
        'user_id' => $this->Auth->user('id'),
        'type' => 'test',
        'entry' => ['test' => '1'],
        'meta' => json_encode(['test' => '1']),
    ];

    $HealthRecord = $this->HealthRecord->patchEntity($HealthRecord,$data);
    dd($HealthRecord);
    //$this->HealthRecord->save($healthRecord);

}

HealthRecord.php

<?php
namespace App\Model\Entity;

use Cake\ORM\Entity;

/**
 * HealthRecord Entity
 *
 * @property int $id
 * @property int $user_id
 * @property string $type
 * @property array $entry
 * @property array $meta
 * @property \Cake\I18n\FrozenTime $created
 * @property \Cake\I18n\FrozenTime $modified
 *
 * @property \App\Model\Entity\User $user
 */
class HealthRecord extends Entity
{

/**
 * Fields that can be mass assigned using newEntity() or patchEntity().
 *
 * Note that when '*' is set to true, this allows all unspecified fields to
 * be mass assigned. For security purposes, it is advised to set '*' to false
 * (or remove it), and explicitly make individual fields accessible as needed.
 *
 * @var array
 */
protected $_accessible = [
    'user_id' => true,
    'type' => true,
    'entry' => true,
    'meta' => true,
    'created' => true,
    'modified' => true,
    'user' => true
];
}

HealthRecordsTables

<?php
namespace App\Model\Table;

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

/**
 * HealthRecords Model
 *
 * @property \App\Model\Table\UsersTable|\Cake\ORM\Association\BelongsTo $Users
 *
 * @method \App\Model\Entity\HealthRecord get($primaryKey, $options = [])
 * @method \App\Model\Entity\HealthRecord newEntity($data = null, array $options = [])
 * @method \App\Model\Entity\HealthRecord[] newEntities(array $data, array $options = [])
 * @method \App\Model\Entity\HealthRecord|bool save(\Cake\Datasource\EntityInterface $entity, $options = [])
 * @method \App\Model\Entity\HealthRecord|bool saveOrFail(\Cake\Datasource\EntityInterface $entity, $options = [])
 * @method \App\Model\Entity\HealthRecord patchEntity(\Cake\Datasource\EntityInterface $entity, array $data, array $options = [])
 * @method \App\Model\Entity\HealthRecord[] patchEntities($entities, array $data, array $options = [])
 * @method \App\Model\Entity\HealthRecord findOrCreate($search, callable $callback = null, $options = [])
 *
 * @mixin \Cake\ORM\Behavior\TimestampBehavior
 */
class HealthRecordsTable extends Table
{

    /**
     * Initialize method
     *
     * @param array $config The configuration for the Table.
     * @return void
     */
    public function initialize(array $config)
    {
        parent::initialize($config);

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

        $this->addBehavior('Timestamp');

        $this->belongsTo('Users', [
            'foreignKey' => 'user_id',
            'joinType' => 'INNER'
        ]);
    }

    /**
     * Default validation rules.
     *
     * @param \Cake\Validation\Validator $validator Validator instance.
     * @return \Cake\Validation\Validator
     */
    public function validationDefault(Validator $validator)
    {
        $validator
            ->integer('id')
            ->allowEmptyString('id', 'create');

        $validator
            ->scalar('type')
            ->maxLength('type', 255)
            ->requirePresence('type', 'create')
            ->allowEmptyString('type', false);

        $validator
            ->requirePresence('entry', 'create')
            ->allowEmptyString('entry', false);

        $validator
            ->requirePresence('meta', 'create')
            ->allowEmptyString('meta', false);

        return $validator;
    }

    /**
     * Returns a rules checker object that will be used for validating
     * application integrity.
     *
     * @param \Cake\ORM\RulesChecker $rules The rules object to be modified.
     * @return \Cake\ORM\RulesChecker
     */
    public function buildRules(RulesChecker $rules)
    {
        $rules->add($rules->existsIn(['user_id'], 'Users'));

        return $rules;
    }
}

Мне надоело очищать кеш модели и даже заходить в файл tmp и очищать там кеш. Также попытался удалить файлы модели и сделать повторный тест, но пока что ничего не работает. Любая помощь будет оценена!

1 Ответ

1 голос
/ 19 марта 2019

Решено, я должен также во множественном числе назвать модель, поэтому для этого случая

вместо

$this->loadModel('HealthRecord');

Должно быть

$this->loadModel('HealthRecords');

и вместо

$HealthRecord =$this->HealthRecord->newEntity();

должно быть

$HealthRecord =$this->HealthRecords->newEntity();
...