目錄
setAttribute
创建文章
queryscope
科普知识:
首頁 後端開發 php教程 queryScope 和 setAttribute 用法

queryScope 和 setAttribute 用法

Jun 23, 2016 pm 01:05 PM

setAttribute

在表单中创建日期,然后直接处理,而不用在controller里面写时间原来的在controller里面写时间

app/Http/Controllers/ArticlesController.php    public function store(Request $requests){        $input = Request::$requests->all();        $input['publish_at']=Carbon::now();  //原来这里是通过直接硬性写时间进去        Articles::create($input);        return redirect('/articles');    }
登入後複製

改为在表单中处理时间

app/Http/Controllers/ArticlesController.php    public function store(Request $requests){ //现在取消掉硬性写时间        Articles::create($requests->all());        return redirect('/articles');    }
登入後複製

(表单)

resources/views/articles/create.blade.php@extends('layout.app')@section('content')    <h1 id="创建文章">创建文章</h1>    {!! Form::open(['url'=>'/articles/store']) !!}            <!--- Title Field --->    <div class="form-group">        {!! Form::label('title', 'Title:') !!}        {!! Form::text('title', null, ['class' => 'form-control']) !!}    </div>    <!--- Content Field --->    <div class="form-group">        {!! Form::label('content', 'Content:') !!}        {!! Form::textarea('content', null, ['class' => 'form-control']) !!}    </div>    <!---  Field --->    <div class="form-group">        {!! Form::label('publish_at', 'publish_at:') !!}        {!! Form::date('publish_at', date('Y-m-d'), ['class' => 'form-control']) !!}  //这里写时间,由用户选择输入    </div>    {!! Form::submit('发表文章',['class'=>'btn btn-primary form-control']) !!}    {!! Form::close() !!}@stop
登入後複製

在数据库里显示的情况

id  title   content publish_at  created_at  updated_at5   我是一篇新文章 你好  2016-05-21 00:00:00 2016-05-21 07:32:48 2016-05-21 07:32:48 //这里的时间只有日期,而没有时分
登入後複製

所以,引申出一个解决办法,在model里面写方法,通过model跟数据库的关联,从而在写入数据库的时候进行时间格式转换(同理可鉴其他数据的处理)

这就是setAttribute 用法

在model里面写,写一个自动处理的function setattribute

app/Articles.phpclass Articles extends Model{    protected $fillable=['title','content','publish_at'];    public function setPublishAtAttribute($date)    //set + 字段名  + attribute 组成的,laravel会自动判断字段名,并且名字要遵循驼峰命名法    {        $this->attributes['publish_at'] = Carbon::createFromFormat('Y-m-d',$date); //调用model的attributes方法来设置    }}
登入後複製

数据库可以看到数据已经生成,并且时间有时分。

id  title   content publish_at  created_at  updated_at6   我是第二篇文章 爱的飒飒大   2016-05-27 08:17:29 2016-05-21 08:17:29 2016-05-21 08:17:29
登入後複製

原来的setattribute是叫setattribute的,不过也支持这样中间插入一个字段,在debug的过程中也可以看到他的转换过程

in Carbon.php line 425at Carbon::createFromFormat('Y-n-j G:i:s', 'Y-m-d-2016-05-27-21 8:21:00', null) in Carbon.php line 368at Carbon::create('Y-m-d', '2016-05-27', null, null, null, null, null) in Carbon.php line 383at Carbon::createFromDate('Y-m-d', '2016-05-27') in Articles.php line 14 at Articles->setPublishAtAttribute('2016-05-27') in Model.php line 2860  //这里调用setPublishAtAttributeat Model->setAttribute('publish_at', '2016-05-27') in Model.php line 447 //这里就转变成setAttributeat Model->fill(array('_token' => '', 'title' => '我是第二篇文章', 'content' => '爱的飒飒大', 'publish_at' => '2016-05-27')) in Model.php line 281at Model->__construct(array('_token' => '', 'title' => '我是第二篇文章', 'content' => '爱的飒飒大', 'publish_at' => '2016-05-27')) in Model.php line 569at Model::create(array('_token' => '', 'title' => '我是第二篇文章', 'content' => '爱的飒飒大', 'publish_at' => '2016-05-27')) in ArticlesController.php line 31at ArticlesController->store(object(Request))
登入後複製

queryscope

将原来的硬性写在controller的处理时间的方法进行修改

app/Http/Controllers/ArticlesController.php    public function index(){        $articles = Articles::latest()->where('publish_at','>=',Carbon::now())->get(); //这里通过直接写时间处理方法来实现数据处理        return view('articles.index',compact('articles'));    }
登入後複製

改为:

    public function index(){//        $articles = Articles::latest()->where('publish_at','< =',Carbon::now())->get();                $articles = Articles::latest()->publish()->get();                 //创造一个新的方法,目的是更灵活也让目前的代码更加简洁和容易理解,                //例如这里就是从articles里获取大概是最后一条数据然后过滤publish时间然后获取最终数据的大概意思,不用再看where什么的了        return view('articles.index',compact('articles'));    }
登入後複製

然后在model articles里面添加scope

app/Articles.php    public function scopePublish($query){  //scope语法限制,scope+刚才的publish函数名字(需要驼峰法命名)        $query->where('publish_at','< =',Carbon::now());  //固定是传入一个$query,暂时的理解是一个数据查询结果,然后使用where过滤数据    }
登入後複製

因为是使用的是model articles的实例,scope命名会让laravel会执行一些自动数据查询,所以能够将数据查询结果$query传入,并且处理

科普知识:

latest()返回的是一个builder对象

Builder|Builder latest(string $column = 'created_at')Add an "order by" clause for a timestamp to the query.Parametersstring  $column Return ValueBuilder|Builder
登入後複製

builder对象是一个特殊的数据对象,是laravel的数据库管理的一个对象,一个builder里面包含了很多数据信息,方便直接使用。

alls方法返回的是一个collection对象

static Collection|Model[] all(array|mixed $columns = array('*'))Get all of the models from the database.Parametersarray|mixed $columns    Return ValueCollection|Model[]
登入後複製

这是collection的格式:

Collection {#136 ▼  #items: array:6 [▼    0 => Articles {#137 ▼      #fillable: array:3 [▶]      #connection: null      #table: null      #primaryKey: "id"      #perPage: 15      +incrementing: true      +timestamps: true      #attributes: array:6 [▼        "id" => 6        "title" => "我是第二篇文章"        "content" => "爱的飒飒大"        "publish_at" => "2016-05-27 08:17:29"        "created_at" => "2016-05-21 08:17:29"  //collection里面的数据是数组包含对象,所以方便调用。        "updated_at" => "2016-05-21 08:17:29"      ]      #original: array:6 [▶]      #relations: []      #hidden: []      #visible: []      #appends: []      #guarded: array:1 [▶]      #dates: []      #dateFormat: null      #casts: []      #touches: []      #observables: []      #with: []      #morphClass: null      +exists: true      +wasRecentlyCreated: false    }    1 => Articles {#138 ▶}    2 => Articles {#139 ▶}    3 => Articles {#140 ▶}    4 => Articles {#141 ▶}    5 => Articles {#142 ▶}  ]}
登入後複製

这是builder的格式:

Builder {#128 ▼  #query: Builder {#127 ▼    #connection: MySqlConnection {#123 ▶}    #grammar: MySqlGrammar {#124 ▶}    #processor: MySqlProcessor {#125}    #bindings: array:6 [▶]    +aggregate: null    +columns: null    +distinct: false    +from: "articles"    +joins: null    +wheres: array:1 [▼ //builder里面包含的数据会存在这里,不过不能直接使用,需要使用像get这样的方法来转换数据。      0 => array:5 [▼        "type" => "Basic"        "column" => "publish_at"        "operator" => ">="        "value" => Carbon {#129 ▼          +"date": "2016-05-21 09:08:10.000000"          +"timezone_type": 3          +"timezone": "UTC"        }        "boolean" => "and"      ]    ]    +groups: null    +havings: null    +orders: array:1 [▶]    +limit: null    +offset: null    +unions: null    +unionLimit: null    +unionOffset: null    +unionOrders: null    +lock: null    #backups: []    #bindingBackups: []    #operators: array:26 [▶]    #useWritePdo: false  }  #model: Articles {#121 ▼    #fillable: array:3 [▶]    #connection: null    #table: null    #primaryKey: "id"    #perPage: 15    +incrementing: true    +timestamps: true    #attributes: []    #original: []    #relations: []    #hidden: []    #visible: []    #appends: []    #guarded: array:1 [▶]    #dates: []    #dateFormat: null    #casts: []    #touches: []    #observables: []    #with: []    #morphClass: null    +exists: false    +wasRecentlyCreated: false  }  #eagerLoad: []  #macros: []  #onDelete: null  #passthru: array:11 [▶]  #scopes: []}
登入後複製
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

AI Hentai Generator

AI Hentai Generator

免費產生 AI 無盡。

熱門文章

R.E.P.O.能量晶體解釋及其做什麼(黃色晶體)
1 個月前 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.最佳圖形設置
1 個月前 By 尊渡假赌尊渡假赌尊渡假赌
威爾R.E.P.O.有交叉遊戲嗎?
1 個月前 By 尊渡假赌尊渡假赌尊渡假赌

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

在PHP API中說明JSON Web令牌(JWT)及其用例。 在PHP API中說明JSON Web令牌(JWT)及其用例。 Apr 05, 2025 am 12:04 AM

JWT是一種基於JSON的開放標準,用於在各方之間安全地傳輸信息,主要用於身份驗證和信息交換。 1.JWT由Header、Payload和Signature三部分組成。 2.JWT的工作原理包括生成JWT、驗證JWT和解析Payload三個步驟。 3.在PHP中使用JWT進行身份驗證時,可以生成和驗證JWT,並在高級用法中包含用戶角色和權限信息。 4.常見錯誤包括簽名驗證失敗、令牌過期和Payload過大,調試技巧包括使用調試工具和日誌記錄。 5.性能優化和最佳實踐包括使用合適的簽名算法、合理設置有效期、

描述紮實的原則及其如何應用於PHP的開發。 描述紮實的原則及其如何應用於PHP的開發。 Apr 03, 2025 am 12:04 AM

SOLID原則在PHP開發中的應用包括:1.單一職責原則(SRP):每個類只負責一個功能。 2.開閉原則(OCP):通過擴展而非修改實現變化。 3.里氏替換原則(LSP):子類可替換基類而不影響程序正確性。 4.接口隔離原則(ISP):使用細粒度接口避免依賴不使用的方法。 5.依賴倒置原則(DIP):高低層次模塊都依賴於抽象,通過依賴注入實現。

如何在系統重啟後自動設置unixsocket的權限? 如何在系統重啟後自動設置unixsocket的權限? Mar 31, 2025 pm 11:54 PM

如何在系統重啟後自動設置unixsocket的權限每次系統重啟後,我們都需要執行以下命令來修改unixsocket的權限:sudo...

解釋PHP中晚期靜態結合的概念。 解釋PHP中晚期靜態結合的概念。 Mar 21, 2025 pm 01:33 PM

文章討論了PHP 5.3中介紹的PHP中的晚期靜態結合(LSB),允許靜態方法的運行時間分辨率調用以更靈活的繼承。 LSB的實用應用和潛在的觸摸

如何用PHP的cURL庫發送包含JSON數據的POST請求? 如何用PHP的cURL庫發送包含JSON數據的POST請求? Apr 01, 2025 pm 03:12 PM

使用PHP的cURL庫發送JSON數據在PHP開發中,經常需要與外部API進行交互,其中一種常見的方式是使用cURL庫發送POST�...

框架安全功能:防止漏洞。 框架安全功能:防止漏洞。 Mar 28, 2025 pm 05:11 PM

文章討論了框架中的基本安全功能,以防止漏洞,包括輸入驗證,身份驗證和常規更新。

自定義/擴展框架:如何添加自定義功能。 自定義/擴展框架:如何添加自定義功能。 Mar 28, 2025 pm 05:12 PM

本文討論了將自定義功能添加到框架上,專注於理解體系結構,識別擴展點以及集成和調試的最佳實踐。

See all articles