Laravel 4:如何将一个WHERE条件应用于Enloquent类的所有查询? [英] Laravel 4: How to apply a WHERE condition to all queries of an Eloquent class?

查看:133
本文介绍了Laravel 4:如何将一个WHERE条件应用于Enloquent类的所有查询?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为表格实现一个已批准的状态,这很简单,基本上如果该行的批准列等于1,则应该检索该行,否则不应该。



问题是,现在我必须通过整个代码库并添加一个WHERE语句(即函数调用),这不仅耗时,而且效率也不高(如果我想要删除该功能等)



我该怎么做?添加 $ this-> where(..) 在这个雄辩的孩子类的构造函数里面不会影响其他的CRUD操作,比如不更新未经批准的行?

解决方案

我发现的最接近的事情是雄辩的查询范围。



即使它需要我的代码稍微改动(前缀查询),它仍然给我很大的灵活性。

这里有一个例子:



在雄辩小孩阶段内创建一个功能:

  class Post Enloquent {

public function scopeApproved($ query)
{
return $ query-> where( 'approved','=',1 / * true * /);
}

}

然后直接使用它:

  $ approvedPosts = Post :: approved() - >< whatever_queries_you_have_here> ;; 

完美工作。没有丑的重复WHERE函数调用。容易修改。更容易阅读( approved()更有意义,其中('approved','=',1)


I'm trying to implement an "approved' state for a table I have, it's pretty straightforward, basically, if the row's approve column equals 1; that row should be retrieved, otherwise it shouldn't.

The problem is, now I have to go through the whole codebase and add a WHERE statement(i.e., function call) which is not only time consuming but also inefficient(if I ever want to remove that feature, etc.)

How can I do that? Is it as easy as adding $this->where(..) inside the Eloquent child class' constructor? Wouldn't that affect other CRUD operations? such as not updating an unapproved row?

解决方案

The closest thing I found is Eloquent query scope.

Even though it requires a minor change in my code(prefixing queries) it still gives me what I'm looking with great flexibility.

Here's an example:

Create a function within the Eloquent child class:

class Post extends Eloquent {

    public function scopeApproved($query)
    {
        return $query->where('approved', '=', 1/*true*/);
    }

}

Then simply use it like this:

$approvedPosts = Post::approved()-><whatever_queries_you_have_here>;

Works perfectly. No ugly repeated WHERE function calls. easy to modify. Much easier to read(approved() makes much more sense than where('approved', '=', 1) )

这篇关于Laravel 4:如何将一个WHERE条件应用于Enloquent类的所有查询?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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