# 數據庫屬性
模型特征用于實現通用功能。
### [](https://octobercms.com/docs/database/traits#hashable)可散列
首次在模型上設置屬性時,會立即對哈希屬性進行哈希處理。要對模型中的屬性進行哈希處理,請應用`October\Rain\Database\Traits\Hashable`特征并`$hashable`使用包含要哈希的屬性的數組聲明一個屬性。
~~~
class User extends Model
{
use \October\Rain\Database\Traits\Hashable;
/**
* @var array List of attributes to hash.
*/
protected $hashable = ['password'];
}
~~~
### [](https://octobercms.com/docs/database/traits#purgeable)可凈化的
創建或更新模型時,清除的屬性不會保存到數據庫中。要清除模型中的屬性,請應用`October\Rain\Database\Traits\Purgeable`特征并`$purgeable`使用包含要清除的屬性的數組聲明屬性。
~~~
class User extends Model
{
use \October\Rain\Database\Traits\Purgeable;
/**
* @var array List of attributes to purge.
*/
protected $purgeable = ['password_confirmation'];
}
~~~
保存模型時,在觸發[模型事件](https://octobercms.com/docs/database/traits#model-events)(包括驗證)之前,將清除定義的屬性。使用`getOriginalPurgeValue`來查找已清除的值。
~~~
return $user->getOriginalPurgeValue('password_confirmation');
~~~
### [](https://octobercms.com/docs/database/traits#encryptable)可加密
與可[散列特征](https://octobercms.com/docs/database/traits#hashable)相似,加密的屬性在設置時會加密,但在檢索到屬性時也會解密。要加密模型中的屬性,請應用`October\Rain\Database\Traits\Encryptable`特征并`$encryptable`使用包含要加密的屬性的數組聲明屬性。
~~~
class User extends Model
{
use \October\Rain\Database\Traits\Encryptable;
/**
* @var array List of attributes to encrypt.
*/
protected $encryptable = ['api_key', 'api_secret'];
}
~~~
> **注意:**作為加密/解密過程的一部分,加密的屬性將被序列化和反序列化。不要說是一個屬性`encryptable`也[`jsonable`](https://octobercms.com/docs/database/model#standard-properties)同時作為`jsonable`進程將試圖解碼已經被去系列化由加密的值。
### [](https://octobercms.com/docs/database/traits#sluggable)慢跑
標簽是有意義的代碼,通常在頁面URL中使用。要為您的模型自動生成唯一的子彈,請應用`October\Rain\Database\Traits\Sluggable`特征并聲明`$slugs`屬性。
~~~
class User extends Model
{
use \October\Rain\Database\Traits\Sluggable;
/**
* @var array Generate slugs for these attributes.
*/
protected $slugs = ['slug' => 'name'];
}
~~~
該`$slugs`屬性應該是一個數組,其中鍵是子段的目標列,值是用于生成子段的源字符串。在上面的示例中,如果將`name`列設置為**Cheyenne**,那么在創建模型之前,**應將**`slug`列設置為**cheyenne**,**cheyenne-2**或**cheyenne-3**等。
要從多個源生成一個段,請傳遞另一個數組作為源值:
~~~
protected $slugs = [
'slug' => ['first_name', 'last_name']
];
~~~
僅在首次創建模型時才生成塊。要覆蓋或禁用此功能,只需手動設置slug屬性:
~~~
$user = new User;
$user->name = 'Remy';
$user->slug = 'custom-slug';
$user->save(); // Slug will not be generated
~~~
`slugAttributes`更新模型時,請使用該方法來生成段塞:
~~~
$user = User::find(1);
$user->slug = null;
$user->slugAttributes();
$user->save();
~~~
### [](https://octobercms.com/docs/database/traits#sluggable-with-softdelete-trait)可搭配SoftDelete特性
默認情況下,生成段時會忽略軟刪除的模型。在恢復軟刪除的模型時,您可能要防止從屬重復。
將`$allowTrashedSlugs`屬性設置為`true`以便在生成新的段時考慮軟刪除的記錄。
~~~
protected $allowTrashedSlugs = true;
~~~
### [](https://octobercms.com/docs/database/traits#revisionable)可修改的
十月模型可以通過存儲修訂來記錄值的更改歷史記錄。要存儲模型的修訂版,請應用`October\Rain\Database\Traits\Revisionable`特征并`$revisionable`使用包含用于監視更改的屬性的數組聲明屬性。您還需要定義一個名為的`$morphMany`[模型關系](https://octobercms.com/docs/database/relations)`revision_history`,該[模型關系](https://octobercms.com/docs/database/relations)引用`System\Models\Revision`名稱為的類`revisionable`,這是修訂歷史記錄數據的存儲位置。
~~~
class User extends Model
{
use \October\Rain\Database\Traits\Revisionable;
/**
* @var array Monitor these attributes for changes.
*/
protected $revisionable = ['name', 'email'];
/**
* @var array Relations
*/
public $morphMany = [
'revision_history' => ['System\Models\Revision', 'name' => 'revisionable']
];
}
~~~
默認情況下,將保留500條記錄,但是可以通過`$revisionableLimit`在模型上聲明一個具有新限制值的屬性來對其進行修改。
~~~
/**
* @var int Maximum number of revision records to keep.
*/
public $revisionableLimit = 8;
~~~
可以像其他任何關系一樣訪問修訂歷史記錄:
~~~
$history = User::find(1)->revision_history;
foreach ($history as $record) {
echo $record->field . ' updated ';
echo 'from ' . $record->old_value;
echo 'to ' . $record->new_value;
}
~~~
修訂記錄可以選擇使用`user_id`屬性來支持用戶關系。您可以`getRevisionableUser`在模型中包括一個方法來跟蹤進行修改的用戶。
~~~
public function getRevisionableUser()
{
return BackendAuth::getUser()->id;
}
~~~
### [](https://octobercms.com/docs/database/traits#sortable)可排序
排序的模型將存儲一個數字值,`sort_order`該值保持集合中每個單獨模型的排序順序。要存儲模型的排序順序,請應用`October\Rain\Database\Traits\Sortable`特征并確保模式中定義了要使用的列(例如:)`$table->integer('sort_order')->default(0);`。
~~~
class User extends Model
{
use \October\Rain\Database\Traits\Sortable;
}
~~~
您可以通過定義`SORT_ORDER`常量來修改用于標識排序順序的鍵名:
~~~
const SORT_ORDER = 'my_sort_order_column';
~~~
使用此`setSortableOrder`方法可以在單個記錄或多個記錄上設置訂單。
~~~
// Sets the order of the user to 1...
$user->setSortableOrder($user->id, 1);
// Sets the order of records 1, 2, 3 to 3, 2, 1 respectively...
$user->setSortableOrder([1, 2, 3], [3, 2, 1]);
~~~
> **注意:**如果將此特征添加到先前已存在數據(行)的模型中,則可能需要先初始化數據集,然后該特征才能正常工作。為此,請手動更新每一行的`sort_order`列,或者對數據運行查詢以將記錄的`id`列復制到該`sort_order`列(例如`UPDATE myvendor_myplugin_mymodelrecords SET sort_order = id`)。
### [](https://octobercms.com/docs/database/traits#simple-tree)簡單樹
一個簡單的樹模型將使用該`parent_id`列維護模型之間的父子關系。要使用簡單樹,請應用`October\Rain\Database\Traits\SimpleTree`特征。
~~~
class Category extends Model
{
use \October\Rain\Database\Traits\SimpleTree;
}
~~~
此特征將自動注入兩個稱為和的[模型關系](https://octobercms.com/docs/database/relations),它等效于以下定義:`parent``children`
~~~
public $belongsTo = [
'parent' => ['User', 'key' => 'parent_id'],
];
public $hasMany = [
'children' => ['User', 'key' => 'parent_id'],
];
~~~
您可以通過定義`PARENT_ID`常量來修改用于標識父項的鍵名:
~~~
const PARENT_ID = 'my_parent_column';
~~~
使用此特征的模型的集合將返回`October\Rain\Database\TreeCollection`添加`toNested`方法的類型。要構建一個預先加載的樹結構,請返回具有預先加載的關系的記錄。
~~~
Category::all()->toNested();
~~~
### 渲染圖
為了渲染所有級別的項及其子項,可以使用遞歸處理
~~~
{% macro renderChildren(item) %}
{% import _self as SELF %}
{% if item.children is not empty %}
<ul>
{% for child in item.children %}
<li>{{ child.name }}{{ SELF.renderChildren(child) | raw }}</li>
{% endfor %}
</ul>
{% endif %}
{% endmacro %}
{% import _self as SELF %}
{{ SELF.renderChildren(category) | raw }}
~~~
### [](https://octobercms.com/docs/database/traits#nested-tree)嵌套樹
該[組嵌套的模型](https://en.wikipedia.org/wiki/Nested_set_model)是使用維護模型中hierachies的先進技術`parent_id`,`nest_left`,`nest_right`,和`nest_depth`列。要使用嵌套集合模型,請應用`October\Rain\Database\Traits\NestedTree`特征。`SimpleTree`此模型的所有特征都固有地可用。
~~~
class Category extends Model
{
use \October\Rain\Database\Traits\NestedTree;
}
~~~
### 創建根節點
默認情況下,所有節點均創建為根:
~~~
$root = Category::create(['name' => 'Root category']);
~~~
另外,您可能會發現自己需要將現有節點轉換為根節點:
~~~
$node->makeRoot();
~~~
您也可以使它的`parent_id`列無效,該列的作用與`makeRoot'相同。
~~~
$node->parent_id = null;
$node->save();
~~~
### 插入節點
您可以通過該關系直接插入新節點:
~~~
$child1 = $root->children()->create(['name' => 'Child 1']);
~~~
或將`makeChildOf`方法用于現有節點:
~~~
$child2 = Category::create(['name' => 'Child 2']);
$child2->makeChildOf($root);
~~~
### 刪除節點
當使用該`delete`方法刪除節點時,該節點的所有后代也將被刪除。請注意,不會為子模型觸發delete[模型事件](https://octobercms.com/docs/database/model#model-events)。
~~~
$child1->delete();
~~~
### 獲取節點的嵌套級別
該`getLevel`方法將返回節點的當前嵌套級別或深度。
~~~
// 0 when root
$node->getLevel()
~~~
### 移動節點
有幾種移動節點的方法:
* `moveLeft()`:找到左側的同級并將其移到左側。
* `moveRight()`:找到正確的同級并將其移到右側。
* `moveBefore($otherNode)`:移至...左側的節點
* `moveAfter($otherNode)`:移至...右側的節點
* `makeChildOf($otherNode)`:將節點設為...的子節點
* `makeRoot()`:將當前節點設為根節點。
### [](https://octobercms.com/docs/database/traits#validation)驗證方式
October模型使用內置的[Validator類](https://octobercms.com/docs/services/validation)。驗證規則在模型類中定義為名為的屬性`$rules`,并且該類必須使用trait`October\Rain\Database\Traits\Validation`:
~~~
class User extends Model
{
use \October\Rain\Database\Traits\Validation;
public $rules = [
'name' => 'required|between:4,16',
'email' => 'required|email',
'password' => 'required|alpha_num|between:4,8|confirmed',
'password_confirmation' => 'required|alpha_num|between:4,8'
];
}
~~~
> **注意**:您也可以將[數組語法](https://octobercms.com/docs/services/validation#validating-arrays)用于驗證規則。
~~~
class User extends Model
{
use \October\Rain\Database\Traits\Validation;
public $rules = [
'links.*.url' => 'required|url',
'links.*.anchor' => 'required'
];
}
~~~
`save`調用方法時,模型會自動驗證自己。
~~~
$user = new User;
$user->name = 'Actual Person';
$user->email = 'a.person@example.com';
$user->password = 'passw0rd';
// Returns false if model is invalid
$success = $user->save();
~~~
> **注意:**您也可以隨時使用`validate`方法驗證模型。
### [](https://octobercms.com/docs/database/traits#retrieving-validation-errors)檢索驗證錯誤
當模型驗證失敗時,會將`Illuminate\Support\MessageBag`對象附加到模型。包含驗證失敗消息的對象。使用`errors`方法或`$validationErrors`屬性檢索驗證錯誤消息收集實例。使用檢索所有驗證錯誤`errors()->all()`。使用檢索*特定*屬性的錯誤`validationErrors->get('attribute')`。
> **注意:**模型利用MessagesBag對象,該對象具有[簡單而優雅](https://octobercms.com/docs/services/validation#working-with-error-messages)的錯誤格式化[方法](https://octobercms.com/docs/services/validation#working-with-error-messages)。
### [](https://octobercms.com/docs/database/traits#overriding-validation)覆蓋驗證
該`forceSave`方法將驗證模型并保存,無論是否存在驗證錯誤。
~~~
$user = new User;
// Creates a user without validation
$user->forceSave();
~~~
### [](https://octobercms.com/docs/database/traits#custom-error-messages)自定義錯誤消息
就像Validator類一樣,您可以使用[相同的語法](https://octobercms.com/docs/services/validation#custom-error-messages)設置自定義錯誤消息。
~~~
class User extends Model
{
public $customMessages = [
'required' => 'The :attribute field is required.',
...
];
}
~~~
您還可以將自定義錯誤消息添加到驗證規則的數組語法中。
~~~
class User extends Model
{
use \October\Rain\Database\Traits\Validation;
public $rules = [
'links.*.url' => 'required|url',
'links.*.anchor' => 'required'
];
public $customMessages = [
'links.*.url.required' => 'The url is required',
'links.*.url.*' => 'The url needs to be a valid url'
'links.*.anchor.required' => 'The anchor text is required',
];
}
~~~
在上面的示例中,您可以將自定義錯誤消息寫入特定的驗證規則(此處使用:)`required`。或者,您可以使用`*`來選擇其他所有內容(此處,我們`url`使用向驗證規則中添加了自定義消息`*`)。
### [](https://octobercms.com/docs/database/traits#custom-attribute-names)自定義屬性名稱
您也可以使用`$attributeNames`數組設置自定義屬性名稱。
~~~
class User extends Model
{
public $attributeNames = [
'email' => 'Email Address',
...
];
}
~~~
### [](https://octobercms.com/docs/database/traits#dynamic-validation-rules)動態驗證規則
您可以通過重寫`beforeValidate`[模型事件](https://octobercms.com/docs/database/model#events)方法來動態應用規則。在這里,我們檢查`is_remote`屬性是否為`false`,然后將`latitude`和`longitude`屬性動態設置為必填字段。
~~~
public function beforeValidate()
{
if (!$this->is_remote) {
$this->rules['latitude'] = 'required';
$this->rules['longitude'] = 'required';
}
}
~~~
### [](https://octobercms.com/docs/database/traits#custom-validation-rules)自定義驗證規則
您也可以使用與Validator服務[相同的方式](https://octobercms.com/docs/services/validation#custom-validation-rules)創建自定義驗證規則。
### [](https://octobercms.com/docs/database/traits#soft-deleting)軟刪除
軟刪除模型時,實際上不會從數據庫中刪除它。而是`deleted_at`在記錄上設置時間戳。要為模型啟用軟刪除,請將`October\Rain\Database\Traits\SoftDelete`特征應用于模型,然后將delete\_at列添加到`$dates`屬性中:
~~~
class User extends Model
{
use \October\Rain\Database\Traits\SoftDelete;
protected $dates = ['deleted_at'];
}
~~~
要將`deleted_at`列添加到表中,可以使用`softDeletes`遷移中的方法:
~~~
Schema::table('posts', function ($table) {
$table->softDeletes();
});
~~~
現在,當您`delete`在模型上調用方法時,該`deleted_at`列將設置為當前時間戳。查詢使用軟刪除的模型時,“已刪除”模型將不包含在查詢結果中。
要確定給定的模型實例是否已被軟刪除,請使用以下`trashed`方法:
~~~
if ($user->trashed()) {
//
}
~~~
### [](https://octobercms.com/docs/database/traits#querying-soft-deleted-models)查詢軟刪除的模型
#### 包括軟刪除的模型
如上所述,軟刪除的模型將自動從查詢結果中排除。但是,您可以使用`withTrashed`查詢中的方法強制將軟刪除的模型顯示在結果集中:
~~~
$users = User::withTrashed()->where('account_id', 1)->get();
~~~
該`withTrashed`方法還可以用于[關系](https://octobercms.com/docs/database/relations)查詢:
~~~
$flight->history()->withTrashed()->get();
~~~
#### 僅檢索軟刪除的模型
該`onlyTrashed`方法將**僅**檢索軟刪除的模型:
~~~
$users = User::onlyTrashed()->where('account_id', 1)->get();
~~~
#### 恢復軟刪除的模型
有時您可能希望“取消刪除”軟刪除的模型。要將軟刪除的模型恢復為活動狀態,請`restore`在模型實例上使用方法:
~~~
$user->restore();
~~~
您也可以`restore`在查詢中使用該方法來快速恢復多個模型:
~~~
// Restore a single model instance...
User::withTrashed()->where('account_id', 1)->restore();
// Restore all related models...
$user->posts()->restore();
~~~
#### 永久刪除模型
有時您可能需要從數據庫中真正刪除模型。要從數據庫中永久刪除軟刪除的模型,請使用以下`forceDelete`方法:
~~~
// Force deleting a single model instance...
$user->forceDelete();
// Force deleting all related models...
$user->posts()->forceDelete();
~~~
### [](https://octobercms.com/docs/database/traits#soft-deleting-relations)軟刪除關系
當兩個相關模型啟用了軟刪除時,您可以通過`softDelete`在[關系定義中定義](https://octobercms.com/docs/database/relations#detailed-relationships)選項來級聯刪除事件。在此示例中,如果用戶模型被軟刪除,則屬于該用戶的注釋也將被軟刪除。
~~~
class User extends Model
{
use \October\Rain\Database\Traits\SoftDelete;
public $hasMany = [
'comments' => ['Acme\Blog\Models\Comment', 'softDelete' => true]
];
}
~~~
> **注意:**如果相關模型不使用軟刪除特征,則將其與`delete`選項一樣對待并永久刪除。
在這些相同的條件下,還原主模型時,所有使用該`softDelete`選項的相關模型也將還原。
~~~
// Restore the user and comments
$user->restore();
~~~
### [](https://octobercms.com/docs/database/traits#soft-delete-with-sluggable-trait)具有刪除特性的軟刪除
默認情況下,當生成條塊時,可拖動特征將忽略軟刪除的模型。為了使模型恢復[減輕](https://octobercms.com/docs/database/traits#sluggable-with-softdelete-trait)痛苦[的拖延部分](https://octobercms.com/docs/database/traits#sluggable-with-softdelete-trait)。
### [](https://octobercms.com/docs/database/traits#nullable)可空
可空屬性設置為`NULL`空時。要使模型中的屬性無效,請應用`October\Rain\Database\Traits\Nullable`特征并`$nullable`使用包含要無效的屬性的數組聲明屬性。
~~~
class Product extends Model
{
use \October\Rain\Database\Traits\Nullable;
/**
* @var array Nullable attributes.
*/
protected $nullable = ['sku'];
}
~~~
- 基本說明
- 基本操作
- October cms 安裝
- 后臺控制器路徑
- 圖標
- 獲取安裝網上的插件/主題
- 插件構造器使用
- 定時任務
- October后臺控制器
- vscode編輯器
- ajax操作
- 使用
- ajax更新組件
- ajax屬性API
- JavaScript API
- ajax綜合使用
- 主題
- 多語言主題
- 安裝市場主題
- 主題程序處理
- 主題
- 頁面
- 部件
- 布局
- 內容
- 組件
- 媒體
- 主題表單操作
- 表單使用
- 表單后端程序處理
- 插件
- 自定義插件
- 插件說明
- 插件導航條
- 插件數據庫設置
- 插件的設置管理
- 插件的配置文件config
- 組件
- app服務
- app容器
- 擴展行為
- 緩存
- Collection類
- Lazy Collections
- Collection方法
- 助手函數
- 數組助手函數
- 路徑助手函數
- 玄樂助手函數
- 其他助手函數
- 錯誤與記錄
- 事件處理
- HTML頁面
- 文件與目錄操作
- 散列和加密
- 郵件
- 郵件內容
- 郵件發送
- 分頁
- 模板解析器
- 動態解析器語法
- 隊列消息
- 請求與輸入
- 響應
- 視圖
- 路由器
- 配置
- 驗證操作
- 處理錯誤消息
- 錯誤消息與視圖
- 可用的驗證規則
- 有條件的驗證規則
- 驗證數組
- 錯誤消息
- 自定義驗證規則
- 模型操作
- 定義模型與其屬性
- 檢索模型
- 插入與更新
- 刪除模型
- 查詢范圍
- 事件操作
- 關聯操作
- 定義關系
- 關系類型
- 多肽關系
- 關系查詢
- 渴望加載
- 插入模型
- 數據庫操作
- 基本用法
- 數據表結構
- 查詢連貫操作
- 結果檢索
- select子句
- 插入更新
- where子句
- 排序,分組,限制和偏移
- 文件附件
- Collection操作
- 屬性操作
- 系列化json
- 數據庫屬性
- 數據庫行為
- 控制器
- 后臺控制器定義
- 后臺頁面
- 后臺組件
- 后臺表單
- 表單組件
- 表單視圖
- 表單行為
- 后臺列表
- 列表行為
- 列表過濾器
- 可用列類型
- 關系行為
- 關系行為類型
- 擴展關系行為
- 列表排序操作
- 導入導出操作
- 用于與權限
- corlate模板修改
- 修改頂部導航
- laravel問題
- 控制器不存在
- 控制器
- 路由組
- laravel筆記
- laravel 安裝
- 偽靜態配置
- 依賴注入 & 控制器
- 中間件
- 路由文件
- 視圖