問題描述
我有新聞模型,當(dāng)我查詢新聞時,我希望它帶來新聞,默認(rèn)狀態(tài) = 1.
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
這可能嗎?我想要的與軟刪除功能非常相似(它獲取deleted_at 不為空的地方,如果需要所有數(shù)據(jù),可以使用Trashed 函數(shù)).
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).
我查看了文檔,但找不到任何有用的信息.此外,我嘗試在 News 模型的構(gòu)造中處理它,但也沒有奏效.
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.
謝謝.
推薦答案
我通常會為此覆蓋 newQuery()
.newQuery()
是 Eloquent 用來構(gòu)造新查詢的方法.
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);
}
}
現(xiàn)在你的 News::all()
只會輸出 status = 1 的新聞.
Now your News::all()
will only output your news with status = 1.
這篇關(guān)于Laravel Eloquent Query Builder 默認(rèn)的 Where 條件的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!