Laravel 4: How to add scope to DB::table?

后端 未结 4 1927
北荒
北荒 2021-01-12 18:38

With Eloquent models adding scopes is easy:

public function scopeMyScope($query)
{
   // Do stuff to that $query
}

But how to add scope to

4条回答
  •  爱一瞬间的悲伤
    2021-01-12 19:00

    DB::table doesn't have support for scopes. What you could do is simply write a little function that does some things with the query and returns it. The syntax isn't as nice but it works:

    function applyScope($query){
        $query->whereNotNull('deleted_at');
        $query->where('foo', 'bar');
        return $query;
    }
    

    And then:

    $query = DB::table('page_views')
        ->where('id', $this->id)
        ->where('agent', 'NOT LIKE', '%bot%');
    $query = applyScope($query);
    $views = $query->count(DB::raw('distinct session, DATE(created_at)'));
    

    Or a bit a shorter syntax:

    $views = applyScope( DB::table('page_views')
                           ->where('id', $this->id)
                           ->where('agent', 'NOT LIKE', '%bot%')
             )->count(DB::raw('distinct session, DATE(created_at)'));
    

提交回复
热议问题