Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have News model, when i query news, i want it brings news where status = 1 as default.

News::all(); // select * from news where status = 1
News::where('anotherColumn',2)->get(); // select * from news where status = 1 and where category = 2

Is this possible? What i want is so similar to soft delete feature (it gets where deleted_at is not null and if all data is wanted withTrashed function can be used).

I looked docs but i couldn't find anything helpful. Also, i tried to handle it in construct at News model but it didn't worked either.

Thanks.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
745 views
Welcome To Ask or Share your Answers For Others

1 Answer

I normally override newQuery() for this. newQuery() is the method that Eloquent use to construct a new query.

class News extends Eloquent {

    public function newQuery($excludeDeleted = true) {
        return parent::newQuery($excludeDeleted)
            ->where(status, '=', 1);
    }

}

Now your News::all() will only output your news with status = 1.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...