目次
setAttribute
queryscope
一般的な科学知識:
ホームページ バックエンド開発 PHPチュートリアル queryScope と setAttribute の使用法

queryScope と setAttribute の使用法

Jun 23, 2016 pm 01:05 PM

setAttribute

コントローラーに時間を書き込む代わりに、フォームに日付を作成し、それを直接処理します。

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');    }
ログイン後にコピー

(form)

resources/views/articles/create.blade.php@extends('layout.app')@section('content')    <h1>创建文章</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 //这里的时间只有日期,而没有时分
ログイン後にコピー

したがって、モデルにメソッドを記述し、モデルをデータベースに関連付けて、書き込み時に時刻形式の変換を実行するという解決策が導き出されます。データベース(他のデータ処理でも同様の原理が使えます)

setAttributeの使い方です

モデルに書いて自動処理関数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 と呼ばれますが、途中でのフィールドの挿入もサポートしています

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

コントローラーの処理に元のハードを記述します。 time メソッド

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'));    }
ログイン後にコピー

次に、モデル記事にスコープを追加します

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

モデル記事のインスタンスが使用されるため、スコープの名前付けにより、laravel が自動データクエリを実行するため、データクエリの結果 $クエリが渡されて処理されます

一般的な科学知識:

latest() はビルダー オブジェクトを返します

Builder|Builder latest(string $column = 'created_at')Add an "order by" clause for a timestamp to the query.Parametersstring  $column Return ValueBuilder|Builder
ログイン後にコピー

ビルダー オブジェクトは特別なデータ オブジェクトであり、laravel のデータベースによって管理されるオブジェクトであり、ビルダーです 多くのデータ情報が含まれています簡単かつ直接的に使用できます。

alls メソッドはコレクション オブジェクトを返します

static Collection|Model[] all(array|mixed $columns = array('*'))Get all of the models from the database.Parametersarray|mixed $columns    Return ValueCollection|Model[]
ログイン後にコピー

これはコレクションの形式です:

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 {#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 搭載アプリ

AI Clothes Remover

AI Clothes Remover

写真から衣服を削除するオンライン AI ツール。

Undress AI Tool

Undress AI Tool

脱衣画像を無料で

Clothoff.io

Clothoff.io

AI衣類リムーバー

AI Hentai Generator

AI Hentai Generator

AIヘンタイを無料で生成します。

ホットツール

メモ帳++7.3.1

メモ帳++7.3.1

使いやすく無料のコードエディター

SublimeText3 中国語版

SublimeText3 中国語版

中国語版、とても使いやすい

ゼンドスタジオ 13.0.1

ゼンドスタジオ 13.0.1

強力な PHP 統合開発環境

ドリームウィーバー CS6

ドリームウィーバー CS6

ビジュアル Web 開発ツール

SublimeText3 Mac版

SublimeText3 Mac版

神レベルのコード編集ソフト(SublimeText3)

JSON Web Tokens(JWT)とPHP APIでのユースケースを説明してください。 JSON Web Tokens(JWT)とPHP APIでのユースケースを説明してください。 Apr 05, 2025 am 12:04 AM

JWTは、JSONに基づくオープン標準であり、主にアイデンティティ認証と情報交換のために、当事者間で情報を安全に送信するために使用されます。 1。JWTは、ヘッダー、ペイロード、署名の3つの部分で構成されています。 2。JWTの実用的な原則には、JWTの生成、JWTの検証、ペイロードの解析という3つのステップが含まれます。 3. PHPでの認証にJWTを使用する場合、JWTを生成および検証でき、ユーザーの役割と許可情報を高度な使用に含めることができます。 4.一般的なエラーには、署名検証障害、トークンの有効期限、およびペイロードが大きくなります。デバッグスキルには、デバッグツールの使用とロギングが含まれます。 5.パフォーマンスの最適化とベストプラクティスには、適切な署名アルゴリズムの使用、有効期間を合理的に設定することが含まれます。

確固たる原則と、それらがPHP開発にどのように適用されるかを説明してください。 確固たる原則と、それらがPHP開発にどのように適用されるかを説明してください。 Apr 03, 2025 am 12:04 AM

PHP開発における固体原理の適用には、次のものが含まれます。1。単一責任原則(SRP):各クラスは1つの機能のみを担当します。 2。オープンおよびクローズ原理(OCP):変更は、変更ではなく拡張によって達成されます。 3。Lischの代替原則(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の実用的なアプリケーションと潜在的なパフォーマ

phpstormでCLIモードをデバッグする方法は? phpstormでCLIモードをデバッグする方法は? Apr 01, 2025 pm 02:57 PM

phpstormでCLIモードをデバッグする方法は? PHPStormで開発するときは、PHPをコマンドラインインターフェイス(CLI)モードでデバッグする必要がある場合があります。

PHPのCurlライブラリを使用してJSONデータを含むPOSTリクエストを送信する方法は? PHPのCurlライブラリを使用してJSONデータを含むPOSTリクエストを送信する方法は? Apr 01, 2025 pm 03:12 PM

PHP開発でPHPのCurlライブラリを使用してJSONデータを送信すると、外部APIと対話する必要があることがよくあります。一般的な方法の1つは、Curlライブラリを使用して投稿を送信することです。

フレームワークセキュリティ機能:脆弱性から保護します。 フレームワークセキュリティ機能:脆弱性から保護します。 Mar 28, 2025 pm 05:11 PM

記事では、入力検証、認証、定期的な更新など、脆弱性から保護するためのフレームワークの重要なセキュリティ機能について説明します。

See all articles