頻繁に使う条件はScopeとして定義しておくことで、再利用が容易になる。
実装
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
<?php namespace App; use Illuminate\Database\Eloquent\Model; class User extends Model { /** * Scope a query to only include popular users. * * @return \Illuminate\Database\Eloquent\Builder */ public function scopePopular($query) { return $query->where('votes', '>', 100); } /** * Scope a query to only include active users. * * @return \Illuminate\Database\Eloquent\Builder */ public function scopeActive($query) { return $query->where('active', 1); } /** * Scope a query to only include users of a given type. * * @return \Illuminate\Database\Eloquent\Builder */ public function scopeOfType($query, $type) //引数を取るScopeも定義できる { return $query->where('type', $type); } } |
使い方
1 2 |
$users = App\User::popular()->active()->orderBy('created_at')->get(); $users = App\User::ofType('admin')->get(); |
参考サイト
Eloquent: Getting Started – Laravel – The PHP Framework For Web Artisans
http://laravel.com/docs/5.1/eloquent#query-scopes