php - Yii2在SQL中插入日期和时间

原文 标签 php mysql yii2

Yii2 insert date and time in sql

I am creating a yii application and I want to insert data into the database but the problem is how to insert date and time. It fails to insert every detail until I remove the date time column from the database .

This is the controller class:

<?php
namespace app\controllers;

use amnah\yii2\user\models\User;
use app\models\Influence;
use Yii;
use yii\filters\AccessControl;
use yii\filters\VerbFilter;
use amnah\yii2\user\controllers\DefaultController as SuperDefault;

class DefaultController extends SuperDefault {

    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'rules' => [
                    [
                        'actions' => ['index', 'confirm', 'resend', 'logout'],
                        'allow' => true,
                        'roles' => ['?', '@'],
                    ],
                    [
                        'actions' => ['account', 'profile','contact', 'resend-change', 'cancel','advertiser_dashboard','influencer_dashboard', 'influenza_info', 'advertiser'],
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                    [
                        'actions' => ['login', 'register','contact','influencer_dashboard', 'advertiser_dashboard','register_advert','forgot', 'reset', 'login-email', 'login-callback'],
                        'allow' => true,
                        'roles' => ['?'],
                    ],
                ],
            ],
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'logout' => ['post', 'get'],
                ],
            ],
        ];
    }


    public function actionInfluenza_info()
    {
        $u_id = Yii::$app->user->id;
        $user = User::findOne($u_id);
           $influence= new Influence(); 

        if ($influence->load(Yii::$app->request->post())) {

                    $influence_data = Yii::$app->request->post('Influence', []);
                 $influence->firstname = $influence_data['firstname'];
                 $influence->lastname = $influence_data['lastname'];
                 $influence->email = $influence_data['email'];
                 $influence->city = $influence_data['city'];
                 $influence->type = $influence_data['type'];
                 $influence->pic = $influence_data['pic'];
                 $influence->address = $influence_data['address'];
                 $influence->country = $influence_data['country'];
                 $influence->gender = $influence_data['gender'];
                   $influence->id = $u_id;

                  $influence->save();

            Yii::$app->session->setFlash("Profile-success", Yii::t("user", "Profile updated"));
            return $this->refresh();
        } else {
            return $this->render('influenza_info', [
                 'user' => $user,

                  'influence' =>$influence
            ]);
        }

    }

    }

this is the model class

  <?php

namespace app\models;

use Yii;
use app\controllers\Expression;
/**
 * This is the model class for table "influence".
 *
 * @property integer $id
 * @property integer $user_id
 * @property string $firstname
 * @property string $lastname
 * @property string $email
 * @property string $city
 * @property string $type
 * @property string $pic
 * @property string $address
 * @property string $country
 * @property string $gender
 */
class Influence extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'influence';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['id', 'user_id', 'firstname', 'lastname', 'email', 'city', 'type', 'pic', 'address', 'country', 'gender'], 'required'],
            [['id', 'user_id'], 'integer'],
       [['firstname', 'lastname', 'email', 'city', 'type', 'pic', 'address', 'country', 'gender'], 'string', 'max' => 30]
        ];
    }
public function beforeSave($insert)
{
if ($this->isNewRecord) { // new record only, otherwise time is inserted every time this record is updated
    $this->created_at = new Expression('NOW()');
}
parent::afterSave($insert);
}
    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'user_id' => 'User ID',
            'firstname' => 'Firstname',
            'lastname' => 'Lastname',
            'email' => 'Email',
            'city' => 'City',
            'type' => 'Type',
            'pic' => 'Pic',
            'address' => 'Address',
            'country' => 'Country',
            'gender' => 'Gender',
            'created_at' => 'Created_at',
        ];
    }
}

the table sql

CREATE TABLE `influence` (
  `id` int(11) NOT NULL,
  `user_id` int(11) NOT NULL,
  `firstname` varchar(30) COLLATE utf8_unicode_ci NOT NULL,
  `lastname` varchar(30) COLLATE utf8_unicode_ci NOT NULL,
  `email` varchar(30) COLLATE utf8_unicode_ci NOT NULL,
  `city` varchar(30) COLLATE utf8_unicode_ci NOT NULL,
  `type` varchar(30) COLLATE utf8_unicode_ci NOT NULL,
  `pic` varchar(30) COLLATE utf8_unicode_ci NOT NULL,
  `address` varchar(30) COLLATE utf8_unicode_ci NOT NULL,
  `country` varchar(30) COLLATE utf8_unicode_ci NOT NULL,
  `gender` varchar(30) COLLATE utf8_unicode_ci NOT NULL,
  `created` timestamp(6) NOT NULL DEFAULT CURRENT_TIMESTAMP
) ;

how do i make it insert automatically. if i try it from my admin it works and gets the dateand time . but with yii it does not.

Answer

To do this I remove the created attribute from the required rule. I then create a beforeSave() method and on a new record insert it with Expression.

public function beforeSave($insert)
{
if ($this->isNewRecord) { // new record only, otherwise time is inserted every time this record is updated
    $this->created = new Expression('NOW()');
}
parent::beforeSave($insert);
}

Make sure you import Expression into the model

Update updated code thanks @crafter

翻译

我正在创建一个yii应用程序,我想将数据插入数据库,但是问题是如何插入日期和时间。在我从数据库中删除日期时间列之前,它无法插入每个详细信息。

这是控制器类:

<?php
namespace app\controllers;

use amnah\yii2\user\models\User;
use app\models\Influence;
use Yii;
use yii\filters\AccessControl;
use yii\filters\VerbFilter;
use amnah\yii2\user\controllers\DefaultController as SuperDefault;

class DefaultController extends SuperDefault {

    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'rules' => [
                    [
                        'actions' => ['index', 'confirm', 'resend', 'logout'],
                        'allow' => true,
                        'roles' => ['?', '@'],
                    ],
                    [
                        'actions' => ['account', 'profile','contact', 'resend-change', 'cancel','advertiser_dashboard','influencer_dashboard', 'influenza_info', 'advertiser'],
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                    [
                        'actions' => ['login', 'register','contact','influencer_dashboard', 'advertiser_dashboard','register_advert','forgot', 'reset', 'login-email', 'login-callback'],
                        'allow' => true,
                        'roles' => ['?'],
                    ],
                ],
            ],
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'logout' => ['post', 'get'],
                ],
            ],
        ];
    }


    public function actionInfluenza_info()
    {
        $u_id = Yii::$app->user->id;
        $user = User::findOne($u_id);
           $influence= new Influence(); 

        if ($influence->load(Yii::$app->request->post())) {

                    $influence_data = Yii::$app->request->post('Influence', []);
                 $influence->firstname = $influence_data['firstname'];
                 $influence->lastname = $influence_data['lastname'];
                 $influence->email = $influence_data['email'];
                 $influence->city = $influence_data['city'];
                 $influence->type = $influence_data['type'];
                 $influence->pic = $influence_data['pic'];
                 $influence->address = $influence_data['address'];
                 $influence->country = $influence_data['country'];
                 $influence->gender = $influence_data['gender'];
                   $influence->id = $u_id;

                  $influence->save();

            Yii::$app->session->setFlash("Profile-success", Yii::t("user", "Profile updated"));
            return $this->refresh();
        } else {
            return $this->render('influenza_info', [
                 'user' => $user,

                  'influence' =>$influence
            ]);
        }

    }

    }


这是模特班

  <?php

namespace app\models;

use Yii;
use app\controllers\Expression;
/**
 * This is the model class for table "influence".
 *
 * @property integer $id
 * @property integer $user_id
 * @property string $firstname
 * @property string $lastname
 * @property string $email
 * @property string $city
 * @property string $type
 * @property string $pic
 * @property string $address
 * @property string $country
 * @property string $gender
 */
class Influence extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'influence';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['id', 'user_id', 'firstname', 'lastname', 'email', 'city', 'type', 'pic', 'address', 'country', 'gender'], 'required'],
            [['id', 'user_id'], 'integer'],
       [['firstname', 'lastname', 'email', 'city', 'type', 'pic', 'address', 'country', 'gender'], 'string', 'max' => 30]
        ];
    }
public function beforeSave($insert)
{
if ($this->isNewRecord) { // new record only, otherwise time is inserted every time this record is updated
    $this->created_at = new Expression('NOW()');
}
parent::afterSave($insert);
}
    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'user_id' => 'User ID',
            'firstname' => 'Firstname',
            'lastname' => 'Lastname',
            'email' => 'Email',
            'city' => 'City',
            'type' => 'Type',
            'pic' => 'Pic',
            'address' => 'Address',
            'country' => 'Country',
            'gender' => 'Gender',
            'created_at' => 'Created_at',
        ];
    }
}


表sql

CREATE TABLE `influence` (
  `id` int(11) NOT NULL,
  `user_id` int(11) NOT NULL,
  `firstname` varchar(30) COLLATE utf8_unicode_ci NOT NULL,
  `lastname` varchar(30) COLLATE utf8_unicode_ci NOT NULL,
  `email` varchar(30) COLLATE utf8_unicode_ci NOT NULL,
  `city` varchar(30) COLLATE utf8_unicode_ci NOT NULL,
  `type` varchar(30) COLLATE utf8_unicode_ci NOT NULL,
  `pic` varchar(30) COLLATE utf8_unicode_ci NOT NULL,
  `address` varchar(30) COLLATE utf8_unicode_ci NOT NULL,
  `country` varchar(30) COLLATE utf8_unicode_ci NOT NULL,
  `gender` varchar(30) COLLATE utf8_unicode_ci NOT NULL,
  `created` timestamp(6) NOT NULL DEFAULT CURRENT_TIMESTAMP
) ;


我如何使其自动插入。如果我从管理员那里尝试的话,它将起作用并且获取日期和时间。但是使用yii却没有。
最佳答案
为此,我从所需规则中删除了创建的属性。
然后,我创建一个beforeSave()方法,并在新记录中将其插入Expression中。

public function beforeSave($insert)
{
if ($this->isNewRecord) { // new record only, otherwise time is inserted every time this record is updated
    $this->created = new Expression('NOW()');
}
parent::beforeSave($insert);
}


确保将Expression导入模型

更新资料
更新的代码感谢@crafter
相关推荐

php - php工匠无法正常工作(laravel 5.1)

php - preg_match_all()不匹配所有可能的出现

php - 在本地数据库中存储Amazon API数据

php - PHP表格检查数组mysql中的复选框值时查询?

php - 无法从数组获取正确的值

php - cakePHP在模型中使用请求/身份验证数据的3个最佳实践(基于帐户的云服务)

php - 什么数据类型可用于在mysql中放置标志(布尔值)?

javascript - 尝试将数据从.php文件传递到.js文件

php - 更改子菜单时如何更改网页背景?

php - Symfony2:如何避免数据库中已经存在重复的实体?