简体   繁体   English

Yii2 防止时间戳行为

[英]Yii2 prevent TimestampBehavior

I am creating a custom Identity interface without created_at property.我正在创建一个没有 created_at 属性的自定义身份接口。 I got an error :我有一个错误:

"name": "Unknown Property",
"message": "Setting unknown property: api\\common\\models\\User::created_at",

I tried to comment the TimestampBehavior, but I got the following error:我试图评论 TimestampBehavior,但出现以下错误:

 "name": "PHP Warning",
 "message": "Invalid argument supplied for foreach()",

I want to know where is the problem.我想知道问题出在哪里。

Model class:模型类:

class User extends ActiveRecord implements IdentityInterface
{
public static function tableName()
{
    return '{{%user}}';
}

public function behaviors()
{
    // return [
    //     TimestampBehavior::className(),
    // ];
}

/**
 * @inheritdoc
 */
public function rules()
{
    return [
        [['purpose'], 'required'],
        [['status'], 'integer'],

    ];
}

}

for the rest controller the action is其余控制器的动作是

           public function actionLogin(){
                . 
                . 
                .

                $api_user = new User();
                $api_user->purpose="app";
                $api_user->status=User::STATUS_ACTIVE;
                if($api_user->save()){
                    $success = true;

                }
            }

This will automatically resolve the issue.这将自动解决问题。 BlameableBehavior and TimestampBehavior BlameableBehaviorTimestampBehavior

// Include these on the start
use yii\behaviors\BlameableBehavior;
use yii\behaviors\TimestampBehavior;
use Carbon\Carbon;

// Paste this function inside the class.

/**
     * @return array
     */
    public function behaviors()
    {
        return [
            'blameable' => [
                'class'              => BlameableBehavior::className(),
                'createdByAttribute' => 'created_by',
                'updatedByAttribute' => 'updated_by',
            ],
            'timestamp' => [
                'class' => TimestampBehavior::className(),
                'createdAtAttribute' => 'created_at',
                'updatedAtAttribute' => 'updated_at',
                'value' => Carbon::now(),
            ],
        ];
    }

NOTE: If you are not using updated_at or updated_by then remove it form the above code注意:如果您不使用updated_atupdated_by则将其从上面的代码中删除

change your Behavior in your model to:modelBehavior更改为:

public function behaviors()

{

    return [

        'timestamp' => [

            'class' => 'yii\behaviors\TimestampBehavior',

            'attributes' => [

                ActiveRecord::EVENT_BEFORE_INSERT => ['updated_at'],

                ActiveRecord::EVENT_BEFORE_UPDATE => ['updated_at'],

            ],

            'value' => new Expression('NOW()'),

        ],           

    ];

 }

if you haven't updated_at also delete it from attributes.如果您还没有updated_at也将其从属性中删除。

You were getting following warning because you've completely removed the return in the behaviors() method.您收到以下警告是因为您已完全删除了behaviors()方法中的返回值。

"name": "PHP Warning", "name": "PHP 警告",

"message": "Invalid argument supplied for foreach()", "message": "为 foreach() 提供的参数无效",

The behaviors method must return an array.行为方法必须返回一个数组。 If you don't want to use any behavior your behaviors() method should return empty array like this:如果您不想使用任何行为,您的behaviors()方法应返回空数组,如下所示:

public function behaviors()
{
    return [];
}

This is also default implementation of behaviors() method in yii\\base\\Component so if you don't need to use any behavior you can simply remove the behaviors() method from your model.这也是yii\\base\\Componentbehaviors()方法的默认实现,因此如果您不需要使用任何行为,您可以简单地从模型中删除behaviors()方法。

Attaching TimestampBehavior to your model when you are not using it means that you add unnecessary overhead.在您不使用时将TimestampBehavior附加到您的模型意味着您会增加不必要的开销。

Example: Rename and prevent time recording or remove properties.示例:重命名并阻止时间记录或删除属性。 Also change the value还要更改值

Rename or delete properties or change value.重命名或删除属性或更改值。

public function behaviors()
{
  return [
    [
        'class' => \yii\behaviors\TimestampBehavior::className(),
        'createdAtAttribute' => 'created_at',
        // 'createdAtAttribute' => 'c_time', //Change the name of the field
        'updatedAtAttribute' => false, //false if you do not want to record the creation time.
        // 'value' => new Expression('NOW()'), // Change the value
    ],
  ];
}

Or或者

      'class' => \yii\behaviors\TimestampBehavior::className(),
      'attributes' => [
          \yii\db\ActiveRecord::EVENT_BEFORE_INSERT => ['created_at'],
          // \yii\db\ActiveRecord::EVENT_BEFORE_UPDATE => [],
      ],

$createdAtAttribute : The attribute that will receive timestamp value Set this property to false if you do not want to record the creation time. $createdAtAttribute :将接收时间戳值的属性 如果您不想记录创建时间,请将此属性设置为 false。

$attributes : List of attributes that are to be automatically filled with the value specified via $value. $attributes$attributes列表,这些属性将自动填充为通过 $value 指定的值。 The array keys are the ActiveRecord events upon which the attributes are to be updated, and the array values are the corresponding attribute(s) to be updated.数组键是要更新属性的 ActiveRecord 事件,数组值是要更新的相应属性。 You can use a string to represent a single attribute, or an array to represent a list of attributes.您可以使用字符串表示单个属性,或使用数组表示属性列表。 For example,例如,

 [ ActiveRecord::EVENT_BEFORE_INSERT => ['attribute1', 'attribute2'], ActiveRecord::EVENT_BEFORE_UPDATE => 'attribute2', ]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM