提问者:小点点

用cakephp 3保存Shell的数据


我错过了什么能够从CakePHP Shell在DB中保存数据?CakePHP 3 Shell能够在DB中保存数据吗?我没看到任何关于这个的留档。

<?php
Namespace App\Shell;

use Cake\Console\Shell;
use Cake\Core\Configure;

// DON'T IF I NEED IT
use Cake\ORM\TableRegistry;
use Cake\ORM\Entity;
use Cake\Datasource\EntityInterface;

class CacheDnsResolverShell extends Shell
{
    public function initialize()
    {
        parent::initialize();
        $this->loadModel('ResolvedHosts');
    }

    public function AddResolvedHost($fqdn, $ip)
    {
        $data = array(
            'fqdn' => $fqdn,
            'ip' => $ip,
            'timestamp' => time()
            );

        // I TRIED THIS, IT DOES NOT WORK
        //$this->ResolvedHosts->save($data);

        // I TRIED ALSO THIS, IT DOES NOT WORK TOO
        $resolvedhost = $this->ResolvedHosts->patchEntity('resolvedhost', $data);

        if ($this->ResolvedHosts->save($resolvedhost)) {
                echo  "$fqdn ($ip) has been added successfully";
        }
    }
}

跑步时:

./bin/cake cache_dns_resolver AddResolvedHost toto 1.1.1.1

我第一次尝试得到:

警告错误:传递给Cake\ORM\Table::save()的参数1必须是Cake\Datasource\EntityInterface的实例,给定数组,在中调用

第二次尝试

警告错误:传递给Cake\ORM\Table::patchEntity()的参数1必须是Cake\Datasource\EntityInterface的实例,警告错误:传递给Cake\ORM\Marshaller::merge()的参数1必须是Cake\Datasource\EntityInterface的实例


共1个答案

匿名用户

提供ResolvedHosts实体:

   public function AddResolvedHost($fqdn, $ip)
    {

        $resolvedhost = $this->ResolvedHosts->newEntity();
        $data = array(
            'fqdn' => $fqdn,
            'ip' => $ip,
            'timestamp' => time()
            );

        // I TRIED THIS, IT DOES NOT WORK
        //$this->ResolvedHosts->save($data);

        // I TRIED ALSO THIS, IT DOES NOT WORK TOO
        $resolvedhost = $this->ResolvedHosts->patchEntity($resolvedhost, $data);

        if ($this->ResolvedHosts->save($resolvedhost)) {
                echo  "$fqdn ($ip) has been added successfully";
        }
    }