php - 如何向 Eloquent 数组添加计数?

标签 php mysql laravel laravel-5

在我的网上商店中,我有搜索组和搜索标签。

每个搜索标签都属于一个搜索组。

搜索标签以多对多关系连接到自行车组。

数据库: enter image description here

我如何使用标签检索我的组:

$searchgroups = SearchGroup::with('searchtags')->get();

现在我想计算每个搜索标签在 tags_bike_groups 中存在的次数并显示它。

enter image description here

这样我就可以显示:

年份

2016 (2)

2017 (5)

2018 (0)

我如何实现这一点?

最佳答案

我明白了。

解决方法是:

$searchgroups = SearchGroup::with('searchtags')->get();
    foreach($searchgroups as $searchgroup) {
        foreach($searchgroup->searchtags as $searchtag) {

            $searchtag->count = count(TagsBikeGroup::where('searchtags_id',$searchtag->id)->get());
        }
    }

然后在你的 View 中你可以得到这样的计数:

{{ $searchtag->count }}

关于php - 如何向 Eloquent 数组添加计数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43868441/

相关文章:

java - 在语句中使用 sql 变量时突然出现 SQL 异常

php - 如何在 Laravel 中按域对路由进行分组

php - 拉维Excel : how to get value of a cell?

php - 如何通过 Laravel 中的多对多关系访问第三个表?

php - Ajax 正在丢失 session

php - sql只在php中插入一些数据

php - 如何将旧的 MySQL 数据库迁移到 Laravel 项目中?

php - Zend_Db_Table 加入查询 vs 数据库 View

PHP, MySQL 查询

PHP 破坏了我的代码