查询关系 Eloquent

Query relationship Eloquent(查询关系 Eloquent)
本文介绍了查询关系 Eloquent的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我有 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:

  1. 急切加载.

  1. 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

Warning: mysqli_query() expects at least 2 parameters, 1 given. What?(警告:mysqli_query() 需要至少 2 个参数,1 个给定.什么?)
INSERT query produces quot;Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result, boolean givenquot;(INSERT 查询产生“警告:mysqli_num_rows() 期望参数 1 为 mysqli_result,给出布尔值;)
prepared statements - are they necessary(准备好的陈述 - 它们是否必要)
Do I need to escape my variables if I use MySQLi prepared statements?(如果我使用 MySQLi 准备好的语句,是否需要转义我的变量?)
Properly Escaping with MySQLI | query over prepared statements(使用 MySQLI 正确转义 |查询准备好的语句)
Is it possible to use mysqli_fetch_object with a prepared statement(是否可以将 mysqli_fetch_object 与准备好的语句一起使用)