dougui4325
2015-12-14 15:35
浏览 41
已采纳

CakePHP在MySQL中的错误日期

I had a field called issue_date in a table that was datetime type in MySQL and I changed to date.

When I am trying to save the date to the database is saving it with
weird years(for example 2196), when the real date is 2003, I made an output of the object before saving it and is showing the real date (2003-06-30)

The field is issue_date.

This is my function to save:

public function populate(){
        $this->tangoModel=$this->loadModel('Tango');
        $tango=$this->tangoModel->getInvoices();
        $this->obrasModel=$this->loadModel('Obras');
        $obras=$this->obrasModel->getObras();
        foreach($tango as $invoice){
        $data[] = ([
        'issue_date' => date('Y-m-d', strtotime($invoice['issue_date'])),
            'type' => $invoice['type']
        ]
        );
        }
        print_r($data);
        $invoices = $this->Invoices->newEntities($data);
        foreach($invoices as $invoice){
        if ($this->Invoices->save($invoice)) {
                $this->Flash->success(__('The invoice has been saved.'));
        };
        }


    }

This is the output of one object of data array:

[0] => Array
    (
        [issue_date] => 2003-06-30,
        [type] => CRE
    )

And this is the output of how is inserted in MySQL

    [{"id":"1",
    "issue_date":"2196-11-06",
    "type":"CRE"
    }]

This is how the field is validated in the InvoicesTable file in /Model/Table:

public function validationDefault(Validator $validator)
    {
        $validator
            ->add('id', 'valid', ['rule' => 'numeric'])
            ->allowEmpty('id', 'create');

        $validator
            ->add('issue_date', 'valid', ['rule' => 'date'])
            ->allowEmpty('issue_date');
         $validator
            ->allowEmpty('type');

        return $validator;
    }
}

This is the entity file Invoice.php in /Model/Entity

   /**
 * Invoice Entity.
 *
 * @property int $id
 * @property \Cake\I18n\Time $issue_date
 * @property string $type
 */
class Invoice 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 = [
        '*' => true,
        'id' => false,
    ];
}

Thanks

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dsajdgjadwqe3247382 2015-12-14 20:34
    已采纳

    It worked adding in the controller:

    use Cake\Database\Type; 
    Type::build('date')->setLocaleFormat('yyyy-MM-dd');
    

    Thanks to ndm

    已采纳该答案
    打赏 评论

相关推荐 更多相似问题