繁体   English   中英

Laravel Eloquent从相关表中获取价值

[英]Laravel Eloquent getting value from related table

我试图获得该主题的所有文章与评论和用户投票的文章,如果存在。

架构如下:

article
id | topic | title | text

article_comments
article_id | comment_id

comments
id | text

votes
id | article_id | user_id

评论通过多对多关系加入。

我现在使用的查询是

    $articles = Article::where('topic', $topic)
                ->orderBy('id', 'desc')->paginate(15);

我需要的是在查询中添加这样的东西:

v.value as 'v_value'...
LEFT JOIN votes v ON (v.article_id=a.id AND v.user_id = :user_id)

有可能,该文章将不会对该用户进行投票 - 在这种情况下,投票表中的行将丢失。

有人能给我一个暗示吗?

感谢您的时间

通常你想使用关系,然后急切加载 votes如:

$articles = Article::where('topic', $topic)
            ->orderBy('id', 'desc')
            ->with('votes')
            ->paginate(15);

现在,你也可以在$articles集合中加载votes

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM