Yii2';行不通
我已经花了好几个小时了,但我还不知道问题出在哪里。 我试图实现一个Yii2';行不通,yii2,yii2-advanced-app,yii2-model,yii-behaviour,Yii2,Yii2 Advanced App,Yii2 Model,Yii Behaviour,我已经花了好几个小时了,但我还不知道问题出在哪里。 我试图实现一个时间行为(和可指责的,但它们现在都不起作用)。我的模型课: <?php namespace common\models; use Yii; use yii\behaviors\BlameableBehavior; use yii\behaviors\TimestampBehavior; use yii\db\Expression; use yii\db\ActiveRecord; /** * This is the
时间行为
(和可指责的
,但它们现在都不起作用)。我的模型课:
<?php
namespace common\models;
use Yii;
use yii\behaviors\BlameableBehavior;
use yii\behaviors\TimestampBehavior;
use yii\db\Expression;
use yii\db\ActiveRecord;
/**
* This is the model class for table "news".
* .... property list
*/
class News extends \yii\db\ActiveRecord
{
/**
* @inheritdoc
*/
public static function tableName()
{
return 'news';
}
/**
* @inheritdoc
*/
public function rules()
{
return [
[['title', 'short_description', 'content'], 'required'],
[['content'], 'string'],
[['title'], 'string', 'max' => 128],
[['short_description'], 'string', 'max' => 255],
];
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
// ... attribute label list
}
public function behaviors()
{
return [
'timestamp' => [
'class' => 'yii\behaviors\TimestampBehavior',
'attributes' => [
ActiveRecord::EVENT_BEFORE_INSERT => ['created_at', 'updated_at'],
ActiveRecord::EVENT_BEFORE_UPDATE => ['updated_at'],
],
'value' => new Expression('NOW()'),
],
'blameable' => [
'class' => BlameableBehavior::className(),
'createdByAttribute' => 'created_by',
'updatedByAttribute' => 'updated_by',
],
];
}
}
更新#2:
我“偶然”注意到,如果我尝试更新模型,问题就存在了。我刚刚创建了一个新模型,所有四列都填充了正确的数据
更新#3:
protected function findModel($id)
{
if (($model = News::findOne($id)) !== null) {
return $model;
} else {
throw new NotFoundHttpException('The requested page does not exist.');
}
}
新闻
表格结构:
确保您实际上正在更改模型字段中的任何内容,因为如果您只是单击“保存”按钮而没有任何更改,则模型不会在数据库中更新(无需更改)正因为如此,时间戳行为不起作用。您能否用负责保存此模型的操作代码更新您的问题?findModel的代码是什么??您说的
news
表仅包含4个字段,但此模型的规则中有3个不同的字段。它能用吗?对不起,我不知道为什么不能用。更新模型时是否更改任何字段?如果您只是单击“保存”而不做任何更改,则不会更新数据库。您不会相信,但我刚才找到了相同的解决方案:(对于我的新手错误,我很抱歉,我以为每次调用更新方法时都会进行更新。非常感谢您的帮助!之后顺便说一句,这绝对是逻辑机制。谢谢。
protected function findModel($id)
{
if (($model = News::findOne($id)) !== null) {
return $model;
} else {
throw new NotFoundHttpException('The requested page does not exist.');
}
}