Vuk*_*vić 21 php laravel eloquent laravel-4
我有News模型,并News有很多评论,所以我在News模型中这样做:
public function comments(){
    $this->hasMany('Comment', 'news_id');
}
但我也有外地trashed的comments表,我只是想选择不丢弃注释.所以trashed <> 1.所以我想知道有没有办法做这样的事情:
$news = News::find(123);
$news->comments->where('trashed', '<>', 1); //some sort of pseudo-code
有没有办法使用上面的方法或我应该写这样的东西:
$comments = Comment::where('trashed', '<>', 1)
    ->where('news_id', '=', $news->id)
    ->get();
rmo*_*bis 28
任何这些应该适合你,选择你最喜欢的:
渴望加载.
$comments = News::find(123)->with(['comments' => function ($query) {
    $query->where('trashed', '<>', 1);
}])->get();
延迟加载
$news = News::find(123);
$comments = $news->comments()->where('trashed', '<>', 1)->get();
不过我不禁注意到,你可能要做的就是处理软删除,Laravel有内置的功能来帮助你:http://laravel.com/docs/eloquent# 软删除
gln*_*eth 15
rmobis的答案就是我所需要的,但它在当前的Laravel 5中引发了错误.你现在必须将它用作关联数组:
$comments = News::find(123)->with(
    ['comments' => function ($query) {$query->where('trashed', '<>', 1);}]
);
花了我一些时间来弄明白,希望这会对别人有所帮助.
阅读Laravel的文档(5.6):https://laravel.com/docs/5.6/eloquent-relationships#querying-relations
您可以在您雄辩的模型文件中完成.这样做:
public function comments_with_deleted()
{
    return $this->belongsTo('Comments', 'id')->where('deleted', 1);
}
public function comments()
{
    return $this->belongsTo('Comments', 'id');
}
像这样打电话:
// for show comments with deleted
$comments = News::find(123)->with('comments_with_deleted');
// for show comments without deleted
$comments = News::find(123)->with('comments');
| 归档时间: | 
 | 
| 查看次数: | 26940 次 | 
| 最近记录: |