前兩天病了。。一直沒寫筆記,今兒個來看看Model在實際開發中的一些簡單使用,首先 我們來為今天的學習做個鋪墊,也當做復習了
准備工作
1、生成表
php artisan make:migration create_articles_table --create=articles
<?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateArticlesTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('articles', function (Blueprint $table) { $table->increments('id'); $table->timestamps(); // 定義字段 $table->string('title'); $table->text('content'); $table->string('author'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('articles'); } }
php artisan migrate
2、創建模型
php artisan make:model Models/Article
使用factory創建測試數據
在實際開發中,我們需要創建表后就開始測試數據,這時我們需要很多數據 不可能一條一條的手動添加 這時需要用到模型工廠-ModelFactory
它位於:\database\factories\ModelFactory.php
<?php /* |-------------------------------------------------------------------------- | Model Factories |-------------------------------------------------------------------------- | | Here you may define all of your model factories. Model factories give | you a convenient way to create models for testing and seeding your | database. Just tell the factory how a default model should look. | */ $factory->define(App\User::class, function ($faker) { return [ 'name' => $faker->name, 'email' => $faker->email, 'password' => str_random(10), 'remember_token' => str_random(10), ]; });
其中laravel默認為我們提供了一個User的factory,下面我們自己寫一個:
$factory->define(App\Models\Article::class, function ($faker){ // 返回我們想要的數據格式 return [ 'title' => $faker->sentence, 'content' => $faker->paragraph, 'author' => $faker->name, ]; });
因為是批量插入,所以我們在模型中指明我們的白名單(之后詳細講):
class Article extends Model { protected $fillable = ['title','content','author']; }
之后 我們在tinker里批量產出數據吧:
php artisan tinker
呼出tinker之后 我們來寫PHP代碼吧:
factory(App\Models\Article::class,20)->create();
enter之后 就生成了20條數據,如此便利神奇,實在好用有木有,快看看數據庫把
查詢操作--取出模型數據
我們可以使用all()方法來獲取所有模型:
Route::get('/articles',function (){ $articles = \App\Models\Article::all(); dd($articles); });
也可以使用條件語句過濾:
Route::get('/articles',function (){ $articles = \App\Models\Article::where('id','<','5')->orderBy('id','desc')->get(); dd($articles); });
我們也可以使用一些條件來取得一條數據:
$articles = \App\Models\Article::where('id',1)->first(); dd($articles);
還有節儉的寫法:
$articles = \App\Models\Article::find(1); dd($articles);
當記錄沒有找到會在頁面上顯示 null,如果我們想捕捉一些信息可以使用findorfail來拋出一個404頁面:
$articles = \App\Models\Article::findOrfail(100); dd($articles);
聚合查詢
如果我們要對查詢結果進行一些計算統計,可以用聚合函數,比如獲取文章總數:
$count = \App\Models\Article::where('id','<=','11')->count(); dd($count);