Cakephp 3:从文件输入

时间:2016-05-10 11:57:47

标签: cakephp cakephp-3.0

我的cakephp3应用程序有问题。我尝试从CSV文件导入一些订阅者。 我使用行为导入我的文件(https://github.com/ProLoser/CakePHP-CSV)。我没有设法加载插件,所以我已将行为文件放在src / Model / Behavior下的项目中。 我已将行为添加到SubscribersTable。

我创建了一个新视图(导入/导出),我已将此方法添加到我的SubscribersController:

public function importExport()
{
    if ($this->request->is('post'))
    {
        $data = $this->request->data;
        if(!empty($data['import_file']['name']))
        {
            $file = $data['import_file'];
            if ((isset($file['tmp_name']) &&($file['error'] == UPLOAD_ERR_OK)))
            {
                $subscribersData = $this->Subscribers->importCsv($file['tmp_name']);
                $entities = $this->Subscribers->newEntities($subscribersData);
                $table = $this->Subscribers;
                $table->connection()->transactional(function () use ($table, $entities) {
                    foreach ($entities as $entity) {
                        $table->save($entity, ['atomic' => false]);
                    }
                });
            }
        }
    }
}

我得到的数据似乎很好,就像实体创建的那样,但是,当我调用$ table-save()时,我有这个错误:

Table "App\Model\Table\SubscribersTable" is not associated with "request"

我已经阅读了有关stackoverflow的其他一些问题,但我不明白为什么会出现这个错误。我是cakephp的新手所以我不明白一切......

如果有人能帮助我......

谢谢!

编辑:在调试期间,似乎行为很奇怪。也许这个错误与我的真实问题无关。 这是调试时间表:

$ table-> save()调用:

        if ($options['atomic']) {
            $success = $connection->transactional(function () use ($entity, $options) {
               return $this->_processSave($entity, $options);
            });
        } else {
             ===> $success = $this->_processSave($entity, $options);
        }
...

$ this-> _processSave call:

    $data = $entity->extract($this->schema()->columns(), true);

并且在提取期间,没有检索到任何列,因为

 public function extract(array $properties, $onlyDirty = false)
{
    $result = [];
    foreach ($properties as $property) {
        if (!$onlyDirty || $this->dirty($property)) {
            $result[$property] = $this->get($property);
        }
    }
    return $result;
}

$ onlyDirty = true和$ this-> dirty($ property))返回false。

因此,当调用此函数时

$success = $this->_insert($entity, $data);

因为数据为空,所以不保存任何内容。

我并不真正理解脏的概念。在文档中,似乎在使用BelongToMany时很有用,但是这个元素与其他表没有链接,所以如果有人能澄清这个概念吗?

SubscribersTable:

    <?php
namespace App\Model\Table;

use App\Model\Entity\Subscriber;
use Cake\ORM\Query;
use Cake\ORM\RulesChecker;
use Cake\ORM\Table;
use Cake\Validation\Validator;

/**
 * Subscribers Model
 *
 */
class SubscribersTable extends Table
{

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

        $this->table('subscribers');
        $this->displayField('email');
        $this->primaryKey('email');

        $options = array(
                // Refer to php.net fgetcsv for more information
                'length' => 0,
                'delimiter' => ',',
                'enclosure' => '"',
                'escape' => '\\',
                // Generates a Model.field headings row from the csv file
                'headers' => true,
                // If true, String $content is the data, not a path to the file
                'text' => false,
        );
        $this->addBehavior('Csv', $options);
    }

    /**
     * Default validation rules.
     *
     * @param \Cake\Validation\Validator $validator Validator instance.
     * @return \Cake\Validation\Validator
     */
    public function validationDefault(Validator $validator)
    {
        $validator
            ->add('email', 'valid', ['rule' => 'email'])
            ->allowEmpty('email', 'create');

        $validator
            ->allowEmpty('contact');

        $validator
            ->allowEmpty('company');

        $validator
            ->allowEmpty('postal_code');

        $validator
            ->add('vip', 'valid', ['rule' => 'boolean'])
            ->allowEmpty('vip');

        $validator
            ->add('indoor', 'valid', ['rule' => 'boolean'])
            ->allowEmpty('indoor');

        $validator
            ->add('live', 'valid', ['rule' => 'boolean'])
            ->allowEmpty('live');

        $validator
            ->add('prod', 'valid', ['rule' => 'boolean'])
            ->allowEmpty('prod');

        $validator
            ->allowEmpty('localisation');

        $validator
            ->allowEmpty('family');

        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->isUnique(['email']));
        return $rules;
    }
}

2 个答案:

答案 0 :(得分:0)

此错误可能来自SubscribersTable.php

如果你在该文件中有$this->request ...,它会抛出该错误,因为它试图找到request作为关联模型,因为它不是从模型调用的有效方法。

或者,如果它在你的控制器中,你可能有$this->Subscribers->request...

如果您像这样引用它,它也可能来自另一个模型:$this->Subscribers->request ...

答案 1 :(得分:-1)

确定。

正如我所想,问题不在于此错误(可能是由于使用了调试器),而是我输入文件的结构。

输入文件必须按照本文档中的说明进行格式化: http://book.cakephp.org/3.0/en/orm/saving-data.html#converting-multiple-records

问题已经解决了!

再次感谢您的帮助!