1.在模型中创建Scopes
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
public $table = "posts";
protected $fillable = [
'id', 'title', 'body', 'status'
];
public function scopeToday($query)
{
return $query->whereDate('created_at', \Carbon\Carbon::today());
}
}
2.使用控制器中的Scopes
Post::today()->get();
3.通过添加参数使Scopes动态化
/**
* Scope created awhile ago
*/
public function scopeToday($query)
{
return $query->whereDate('created_at', \Carbon\Carbon::today());
}
/**
* New Dynamic Scope
*/
public function scopeStatus($query, $type)
{
return $query->where('status', $type);
}
4.控制器中使用两者
Post::status(1)->today()->get();
发表评论 取消回复