問題描述
我有 News
模型,而且 News
有很多評論,所以我在 News
模型中做了這個:
I have News
model, and News
has many comments, so I did this in News
model:
public function comments(){
$this->hasMany('Comment', 'news_id');
}
但是我在 comments
表中也有字段 trashed
,我只想選擇沒有被刪除的評論.所以 廢棄了 <>1
.所以我想知道有沒有辦法做這樣的事情:
But I also have field trashed
in comments
table, and I only want to select comments that are not trashed. So trashed <> 1
. So I wonder is there a way to do something like this:
$news = News::find(123);
$news->comments->where('trashed', '<>', 1); //some sort of pseudo-code
有沒有辦法使用上述方法,或者我應該寫這樣的東西:
Is there a way to use above method or should I just write something like this:
$comments = Comment::where('trashed', '<>', 1)
->where('news_id', '=', $news->id)
->get();
推薦答案
這些都適合你,選擇你最喜歡的:
Any of these should work for you, pick the one you like the most:
急切加載.
Eager-loading.
$comments = News::find(123)->with(['comments' => function ($query) {
$query->where('trashed', '<>', 1);
}])->get();
您可以通過 use($param)
方法將參數注入查詢函數,這允許您在運行時使用動態查詢值.
You can inject the parameter to query function by use($param)
method, that allows you to use dynemic query value at runtime.
延遲加載
$news = News::find(123);
$comments = $news->comments()->where('trashed', '<>', 1)->get();
<小時>
不過,我忍不住注意到,您可能想做的是處理軟刪除,而 Laravel 有內置功能可以幫助您:http://laravel.com/docs/eloquent#soft-deleting
這篇關于查詢關系 Eloquent的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!