【问题标题】:Laravel migration with relationLaravel 迁移与关系
【发布时间】:2018-06-21 11:43:15
【问题描述】:

我是 Laravel 的新手,所以我不知道这个问题到底是什么。所以我将详细描述它。首先我有2个表ArticleComment,关系1-1,这意味着一篇文章只能有1个cmets。 代码是:

$article = Article::with('comments')

结果是

以下是我得到的评论属性:

但是现在,我希望构建器仅选择文章内容长度 > 其评论内容长度的文章。在 MySQL 语句中是

"Select from articles a where length(a.content) > (Select length(c.content) from comments c where c.article_id = a.id)

我已尝试使用 rawjoin 并且它有效。但我想知道我可以对“with”关系做同样的事情吗?我该怎么做?

【问题讨论】:

  • 文章内容长度 > 文章内容长度?没有意义。
  • @Wreigh 抱歉,它的评论内容长度。这是我的错
  • 我认为,您的规范在技术上是错误的。 with 加载关系。但是您要做的是根据其关系检索模型。 Article::with('comments') 表示加载所有文章及其相关评论。我认为最好改用wheres,你不觉得吗?
  • 你能写出完整的代码吗?我想获得条件取决于它与 cmets 的关系的文章(其中长度(article.content)>长度(article.comment.content))
  • 要获取文章内容长度大于评论内容长度的所有文章吗?

标签: mysql laravel migration relation


【解决方案1】:

试试这个

$article = Article::where(DB::raw('length(content)','>' ,DB::raw('Select length(content) from cmets where article_id = id'))->with (['cmets'])->get();

【讨论】:

  • 正如我在问题中所说,我不想找到 raw 和 join 的方式
  • 但是您的查询可能没有被 eloquent 函数覆盖,或者您可以使用带有定义文章和评论对象的 db raw 或集合过滤器。 laravel.com/docs/5.5/collections#method-filter
  • 不,请阅读我的问题。我知道我可以使用生的。我已经使用了原始和成功。但我想找到另一种方式(不使用原始方式)。
【解决方案2】:

试试这个:

$articles = Article::with('comments')->get();

$onlyWithLongerContent = $articles->filter(function($article) {
    return strlen($article->content) > strlen($article->comments->content);
})->values();

我会尝试另一种方式,但这是一种方式。

另一种方法可能是使用 join 和 where 子句构建查询。

【讨论】:

  • 是的,它似乎接近我的预期。但问题是我想 Article::with('cmets')->mycondition()->paginate();因此,如果我使用 get() 那么它不能分页,因为它现在是集合。分页仅适用于构建器
  • 如果你想分页,我建议你使用带有查询生成器的原始查询。
  • 嗯,我用过。 (我在问题中说过)。我只想知道我是否可以使用“with”来代替?
  • 不,你不能。 with 用于预加载关系;例如,急切加载与文章相关的所有 cmets。在您的情况下,您正在尝试过滤模型查询的结果,这超出了 with 的范围,它操纵或专注于 relationship 方面。
【解决方案3】:

你有没有尝试过这样的事情:

/**
 * Get the comments.
 *
 * @return 
 */
public function comments()
{
    return $this->hasmany('App\Comments')->where('content', '!=', null);
}

或者

/**
 * Get the comments
 *
 * @return
 */
public function comments()
{
    return $this->hasManyThrough('App\Comments', 'App\Articles', 'id', 'article_id')->where('content', '!=', null);
}

【讨论】:

    猜你喜欢
    • 2012-11-12
    • 2017-01-04
    • 2021-12-27
    • 1970-01-01
    • 2015-09-29
    • 2020-04-13
    • 2018-10-21
    • 2016-09-17
    • 2020-05-08
    相关资源
    最近更新 更多