php - Laravel eloquent 获取关系数

标签 php laravel

我使用 Laravel 5.3。

我有 2 张 table :

Articles
---------
id
cat_id
title


Category
---------
id
parent_id
title

我已经在我的模型中定义了我的关系:
// Article model
public function category()
{
    return $this->belongsTo(Category::class);
}

// Category model
public function children() 
{
    return $this->hasMany(Category::class, 'parent_id', 'id');
}   

有没有一种简单的方法使用 Eloquent 来列出一个包含文章计数的类别。难点在于我想对 id_parent = 0 所在的类别进行分组,即我只想显示带有子项文章数的父类别。

我试过这样的事情:
    $category = new \App\Models\Category();
    $categoryTable = $category->getTable();

    return $category->leftJoin('article', 'article.cat_id', '=', 'category.id')
        ->whereIn('article.cat_id', function($query)
            {
                $query->select('cat_id')
                    ->from('categories')
                    ->where('categories.parent_id', ???)
                    ->orWhere($this->tableName .'.cat_id', $id);
            })
        ->groupBy('cat_id');

但是我迷路了...

最佳答案

您可以使用 withCount() .从 5.3 版本开始可用

有关 Eloquent 访问的更多信息:https://laravel.com/docs/5.3/eloquent-relationships

关于php - Laravel eloquent 获取关系数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41165726/

相关文章:

javascript - 我如何使 PHP/HTML 图像在单击时显示原始大小?

php - Laravel - 如果值包含某个字符串(从搜索输入中获取),则查询模型

php - PHP/JavaScript/.NET 中的 MAC 地址?

php - Laravel Eloquent 多重关系找到小于 x 天的最大日期,使用预加载

javascript - Vue JS 使用 Modal 加载动态数据问题

php - 在 Repository 类中注入(inject) DatabaseManager

php - Laravel 3 和 Composer 中未找到类

php - Cassandra CQL : Batch select

javascript - Angularjs JSON Unicode 字符

javascript - 无法让我的下拉菜单在基于 Bootstrap 的 Wordpress 主题中工作