Laravel 4:如何将范围添加到DB :: table? [英] Laravel 4: How to add scope to DB::table?

查看:179
本文介绍了Laravel 4:如何将范围添加到DB :: table?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用雄辩的模型添加范围很容易:

With Eloquent models adding scopes is easy:

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

但是如何将范围添加到DB::table?

But how to add scope to DB::table?

我使用此查询获取网页浏览量:

I use this query to get page views:

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

我还显示了其他查询中最受欢迎的页面,但是具有相同的where条件.因此,我只想定义我的where条件一次,然后在所有其他页面视图DB::table查询中重用它们.

I also show the most popular pages etc with other queries, but with the same where conditions. So I would like to only define my where conditions once and reuse them in all other page view DB::table queries.

推荐答案

DB::table不支持范围.您可以做的就是简单地编写一个小函数,对查询执行一些操作并将其返回.语法不是很好,但是可以工作:

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;
}

然后:

$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)'));

或更简短的语法:

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

这篇关于Laravel 4:如何将范围添加到DB :: table?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆