Laravel 4: How to apply a WHERE condition to all queries of an Eloquent class?

前端 未结 3 1768
我在风中等你
我在风中等你 2021-02-02 16:55

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,

3条回答
  •  死守一世寂寞
    2021-02-02 17:12

    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()->;
    

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

提交回复
热议问题