laravel迁移

xam8gpfp  于 2021-06-25  发布在  Mysql
关注(0)|答案(3)|浏览(254)

我是新来的拉威尔,所以我不知道到底是什么问题。所以我会详细描述一下。首先我有两个表文章和评论,关系为1-1,这意味着一篇文章只能有一个评论。代码是:

$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)

我试过用raw和join,效果不错。但我想知道,我能用“with”关系做同样的事吗?我该怎么做?

y1aodyip

y1aodyip1#

你试过这样的方法吗:

/**
 * 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);
}
bvn4nwqk

bvn4nwqk2#

试试这个
$article=article::where(db::raw('length(content)',>',db::raw('select length(content)from comments where article_id=id'))->with(['comments'])->get();

7tofc5zh

7tofc5zh3#

试试这个:

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

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

我会试着想另一种方法,但这是一种方法。
另一种方法可能是使用join和where子句为其构建查询。

相关问题