一些常用的模型屬性

finecho發表於2018-12-26

@這是小豪的第三篇文章
今天整理了一下模型屬性,權當一個工具使用,方便查閱,歡迎收藏,哈哈。


connection

 /**
  * 為模型指定一個連線名稱。
  *
  * @var string
  */
 protected $connection = 'connection-name';

table

/**
 * 為模型指定一個表名。
 *
 * @var string
 */
 protected $table = 'users';

primaryKey

/**
 * 為模型指定主鍵。
 *
 * @var string
 */
 protected $primaryKey = 'user_id';

keyType

 /**
  * 自定義主鍵型別。
  *
  * @var string
  */
 protected $keyType = 'string';

incrementing

 /**
  * 如果使用的是非遞增或者非數字的主鍵。
  *
  * @var bool
  */
 public $incrementing = false;

with

class Post extends Model
{
 /**
  * 載入模型關聯資料。
  * 
  * @var array
  */
  protected $with = [
      'comments'
  ];
}

《模型關聯給我們帶來了哪些便利》 有介紹 with 的用法噢。

withCount

class Post extends Model
{
 /**
  * 載入模型關聯資料數量。
  * 
  * @var array
  */
  protected $withCount = [
      'comments'
  ];
}

timestamps

 /**
  * 執行模型是否自動維護時間戳.
  *
  * @var bool
  */
 public $timestamps = false;

fillable

/**
 * 可以被批量賦值的屬性。
 *
 * @var array
 */
 protected $fillable = ['name', 'age'];

guarded

 /**
  * 不可被批量賦值的屬性,當 $guarded 為空陣列時則所有屬性都可以被批量賦值。
  *
  * @var array
  */
 protected $guarded = ['price'];    

guardedfillable,在當前模型中只能存在一者噢。

CREATED_AT

 /**
  * 建立時間戳欄位名稱。
  *
  * @var string
  */
 const CREATED_AT = 'created_at';   

UPDATED_AT

 /**
  * 更新時間戳欄位名稱。
  *
  * @var string
  */
 const UPDATED_AT = 'updated_at';   

attributes

 const STATUS_CREATED = 'created';

 /**
  * 給定欄位預設值。
  *
  * @var array
  */
 protected $attributes = [
     'status' => self::STATUS_CREATED,
 ];

casts

 /**
  * 欄位轉換為對應的型別。
  *
  * @var array
  */
 protected $casts = [
    'id' => 'integer',
    'settings' => 'array',
    'is_admin' => 'boolean',
 ];

dates

 /**
  * 需要轉換成日期的屬性。
  *
  * @var array
  */
 protected $dates = ['deleted_at'];

dateFormat

 /**
  * 模型中日期欄位的儲存格式。
  *
  * @var string
  */
 protected $dateFormat = 'U';

不清楚 U 是什麼意思的,請看 Date/Time 函式

appends

 /**
  * 追加到模型陣列表單的訪問器。
  *
  * @var array
  */
 protected $appends = ['is_admin'];

一般情況下 appends 都是與 訪問器連用的。

hidden

 /**
  * 陣列中的屬性會被隱藏。
  *
  * @var array
  */
 protected $hidden = ['password'];

visible

 /**
  * 陣列中的屬性會被展示。
  *
  * @var array
  */
 protected $visible = ['first_name', 'last_name'];

dispatchesEvents

 /**
  * 模型的事件對映。
  *
  * @var array
  */
 protected $dispatchesEvents = [
     'saved' => UserSaved::class,
     'deleted' => UserDeleted::class,
 ];

forceDeleting

 /**
  * 指示模型當前是否強制刪除。
  *
  * @var bool
  */
 protected $forceDeleting = false;

perPage

 /**
  * 預設分頁數量。
  *
  * @var int
  */
 protected $perPage = 50;

touches

 /**
  * 更新新增的關聯模型的 updated_at 欄位。
  *
  * @var array
  */
 protected $touches = ['post'];

結束語

歡迎在評論區大家補充噢。

本作品採用《CC 協議》,轉載必須註明作者和本文連結

finecho # Lhao

相關文章