【问题标题】:Search query and count results many to many relationships in laravel在 laravel 中搜索查询并计算结果的多对多关系
【发布时间】:2018-04-06 00:59:29
【问题描述】:

我正在使用插件 TokenInput 来执行搜索标签。 我有 2 个具有多对多关系的表。表:故事、标签和数据透视表:story_tag。我执行一个搜索查询:

$term = request('q');
$tags = \App\Tag::where('slug', 'LIKE', '%' . $term . '%')->get();

return response()->json($tags->toArray());

它正在工作。现在,我想计算数据透视表 story_tag 中的标签数量并将结果显示如下:

tagNamea - 69

tagNameb - 9

...

我尝试了很多搜索,但没有得到想要的结果。怎么做?有什么帮助吗?谢谢。

更新:

关系模型:

故事模型:

public function tags()
{
    return $this->belongsToMany('App\Tag');
}

标签模型:

public function stories()
{
    return $this->belongsToMany('App\Story');
}

【问题讨论】:

  • 这是什么tagNamea
  • 是从Tag表查询的结果。数字 69 是数据透视表中的计数。它对应于数据透视表中标签的出现次数。
  • 您能否告诉我们您是如何定义模型中 Story 和 Tag 之间的关系的?
  • 我已经在上面更新了。

标签: laravel search relationship


【解决方案1】:

你需要有这样的关系

public function stories()
{
     return $this->belongsToMany('App\Story', 'story_tag', 'tag_id', 'story_id');
}

我不知道你需要什么回应,但你必须像上面提到的关系

【讨论】:

    【解决方案2】:

    只要您有一个 eloquent 集合,您就可以对该集合使用 count 方法。

    例如:

    $count = $tags->count();
    

    如果您的 $tags 是一个集合,那么您将获得 $count 中的标签数量。

    【讨论】:

      【解决方案3】:

      您可以使用$tags->count()count() 方法会统计集合的所有结果。

      【讨论】:

        猜你喜欢
        • 2013-09-30
        • 2015-10-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-11-02
        • 2015-05-29
        • 1970-01-01
        • 2016-11-03
        相关资源
        最近更新 更多