How can I implement single table inheritance using Laravel's Eloquent?

前端 未结 2 1055
清歌不尽
清歌不尽 2020-11-29 23:23

Currently I have a model class named Post.

class Post extends Eloquent {

    protected $table = \'posts\';
    protected $fillable = array(\'us         


        
2条回答
  •  渐次进展
    2020-11-29 23:54

    from Laravel 5.2, Global Scope is available:

    class Article extends Post
    {
        protected $table = 'posts';
    
        protected static function boot()
        {
            parent::boot();
    
            static::addGlobalScope('article', function (Builder $builder) {
                $builder->where('type', 'article');
            });
    
            static::creating(function ($article) {
                $article->type = 'article' 
            }); 
        }
    }
    

    where type = 'article' is added to all query of Article just like SoftDeletes.

    >>> App\Article::where('id', 1)->toSql()
    => "select * from `posts` where `id` = ? and `type` = ?"
    

    Actually laravel provide SoftDeletes trait using this feature.

提交回复
热议问题