การใช้งาน TimestampBehavior ใน Model

wave
มานพ กองอุ่น 10 เม.ย. 2016 10:53:59 10,125

TimestampBehavior คืออะไร?

TimestampBehavior เป็นตัวช่วยในการบันทึกข้อมูล Timestamp ลงในฐานข้อมูลในกรณีที่มีการเพิ่มหรือแก้ไขข้อมูล ทำให้สะดวกในการเขียนโปรแกรม โดยไม่ต้องเขียนในส่วนโปรแกรมให้ insert/update ซึ่ง behavior นี้จะกำหนดใน Model

ค่าเริ่มต้นของ field/attribute ที่จะทำงานอัตโนมัติคือ

created_at เมื่อเพิ่มใหม่
updated_at เมื่อเพิ่มใหม่ และมีการแก้ไข

ตัวอย่างการใช้งาน

ตัวอย่างที่ 1 ในกรณีที่ behaviors มีเพียง TimstampBehavior

use yii\behaviors\TimestampBehavior;

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

ตัวอย่างที่ 2 ในกรณีใช้ TimestampBehavior ร่วมกับตัวอื่น

use yii\behaviors\TimestampBehavior;

public function behaviors()
{
   return [
        
            'timestamp' => [
                'class' => TimestampBehavior::className(),
            ],
            //other behaviors
   ];
}

ตัวอย่างที่ 3 ในกรณีที่attribute ที่แตกต่างไปจากค่าเริ่มต้น และต้องมีการกำหนดค่า

use yii\behaviors\TimestampBehavior;
use yii\db\Expression;

public function behaviors()
{
   return [
        
            'timestamp' => [
                'class' => TimestampBehavior::className(),
                'createdAtAttribute' => 'create_time',
                'updatedAtAttribute' => 'update_time',
                'value' => new Expression('NOW()'),//กำหนดค่า หรืออาจใช้ค่าอย่างอื่นที่ return เป็น timestamp ก็ได้
            ],
            //other behaviors
   ];
}

หรือ

use yii\behaviors\TimestampBehavior;
use yii\db\Expression;

public function behaviors()
{
    return [
        [
            'class' => TimestampBehavior::className(),
            'createdAtAttribute' => 'create_time',
            'updatedAtAttribute' => 'update_time',
            'value' => new Expression('NOW()'),
        ],
    ];
}

ตัวอย่างที่ 4 ในกรณีมีการ update ข้อมูล สามารถใช้ method พิเศษได้ เช่น

$model->touch('creation_time');

เป็นการ update ใน attribute creation_time ให้เป็น timestamp ปัจจุบัน

สรุป

TimestampBehavior ช่วยให้เราไม่ต้องเขียนโปรแกรมในส่วน Controller มากนักช่วยให้เกิดความสะดวกและรวดเร็วต่อการเพิ่ม timestamp ลงใน field created_at และ updated_at


ความคิดเห็น

หากบทเรียนรู้มีความผิดพลาดประการใด หรือมีข้อเสนอแนะกรุณาแจ้ง contact@programmerthailand.com

เขียนบทเรียนรู้ของคุณ

รายละเอียด
  • ดู 10,125
  • รักเลย 0
  • หมวดหมู่ Yii Framework 2 (Yii2)
  • เขียนเมื่อ
  • แก้ไขเมื่อ
  • Tags yii timestamp behavior
ข้อมูลผู้เขียน
มานพ กองอุ่น

มานพ กองอุ่น

เป็นสมาชิกเมื่อ: 18 ธ.ค. 2009

เนื้อหาที่เกี่ยวข้อง