繁体   English   中英

雄辩的多对多关系,并使用数据透视表作为单独的模型

[英]Eloquent many-to-many relationship and using pivot table as separate model

在构建laravel Web应用程序时,我遇到了一个有趣的问题,我认为应该有一种最佳实践来解决此类问题,而无需重新发明轮子。

基本上,我有多对多关系:

帖子有很多类别,但同时类别也可以有很多帖子。 属于该帖子的每个类别都可以有“投票”。 这些投票通常不属于类别,而仅属于category_post数据透视表条目。

我的问题是:我应该创建一个单独的模型“ CategoryPost”,然后将其与“投票”表使用一对多关系,那里有一种更为优雅的实现方式。

我还试图使查询过程尽可能具有表现力。

基本上我在类别类中编写了这样的代码:

public function votes()
{
    // find id of pivot table column
    $categoryPost = CategoryPost::where('skill_id', $this->id)->first();
    if($categoryPost) {

       $likes = Like::where('likeable_id', $categoryPost->id)->get();

        if(count($likes)) {
            return count($likes);
        } else {
            return 0;
        }
    } else {
        return 0;
    }
}

并同时添加了CategoryPost类。 现在可能是最优雅的解决方案,但是如果有更好的建议,那就太好了。

从Laravel关于口才关系L 5.2的文档中:

计算关系结果

如果您想计算一个关系的结果数而不实际加载它们,则可以使用withCount方法,该方法将在结果模型上放置一个{relation} _count列。

例如:

$posts = App\Post::withCount('comments')->get();

foreach ($posts as $post) {
    echo $post->comments_count;
}

您可以添加检索多个关系的“计数”,以及向查询添加约束:

$posts = Post::withCount(['votes', 'comments' => function ($query) {
    $query->where('content', 'like', 'foo%');
}])->get();

echo $posts[0]->votes_count;
echo $posts[0]->comments_count;

暂无
暂无

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

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