laravel實現Model的setAttribute、getAttribute、scopeQuery方法

首先要定義一個Model

1.getAttribute的實現

getFooAttribute在模型上建立一個方法,其中Foo包含您要訪問的列的「studly」外殼名稱。在這個例子中,咱們將爲first_name屬性定義一個訪問器。嘗試檢索sex屬性值時,Eloquent會自動調用訪問者:php

<?php
namespace App;
use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    public function getSexAttribute($sex)
    {
        if ($sex == 1) return '男';
        if ($sex == 2) return '女';
        return '未知';
    }
}複製代碼

查詢出來模型之後獲取sex,將是男或者女或者未知 bash

$user = App\User::find(1);
$sex = $user->sex;
dd($sex); // 男複製代碼

2.setAttribute的實現

getFooAttribute在模型上建立一個方法,其中Foo包含您要訪問的列的「studly」外殼名稱。在這個例子中,咱們將爲first_name屬性定義一個訪問器。嘗試檢索sex屬性值時,Eloquent會自動調用訪問者:ui

<?php
namespace App;
use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    public function setSexAttribute($sex)
    {
       $this->attributes['sex'] = $sex;
    }
}複製代碼

查詢出來模型之後獲取sex,將是男或者女或者未知 this

$user = App\User::find(1);
$user->sex = '我是sex';
dd($user->sex);   // 我是sex複製代碼

3.scopeQuery的實現

本地範圍容許您定義可在整個應用程序中輕鬆重用的常見約束集。例如,您可能須要常常檢索全部被視爲「受歡迎」的用戶。要定義範圍,請使用Eloquent模型方法做爲前綴scope。範圍應始終返回查詢構建器實例:spa

<?php
namespace App;
use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    public function scopeSex($query)
    {
        return $query->where('sex', 1);
    }
}複製代碼

定義後,能夠在查詢模型時調用該方法。可是,scope調用方法時不該包含前綴。您甚至能夠將調用連接到各類範圍,如:code

$users = App\User::sex()->orderBy('created_at')->get();複製代碼

純原創,但願能夠對你們有幫助,若有疑問,歡迎評論 

相關文章
相關標籤/搜索