如何通过Eloquent获得嵌套计数?

时间:2017-01-15 10:28:53

标签: laravel eloquent

我有简单的嵌套树模型:

Page table

id
owner_id
title

任何页面都可以通过键owner_id具有相似的页面,并引用相同的表记录。

如何通过Eloquent获取一些包含id嵌套页面数量的页面?

在本机SQL中,我可以这样做:

SELECT pages.*, count(subPage.id) AS childCount
FROM pages AS page
LEFT JOIN pages AS subPage ON (subPage .owner_id = page.id)
....

这样的事情:

$page->childsCount将返回相关子页面的数量。

4 个答案:

答案 0 :(得分:2)

假设您已经定义了pages()关系,则可以使用withCount()方法:

Page::withCount('pages')->first();
  

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

答案 1 :(得分:0)

通过CameraCamera cam; void Start() { cam = GameObject.Find("NameOfCameraGameObject").GetComponent<Camera>(); } void Update() { if (Input.touchCount > 0) { RaycastHit2D hit = Physics2D.Raycast(cam.ScreenToWorldPoint(Input.GetTouch(0).position), Vector2.zero); if (hit && hit.collider != null && hit.collider.name == "leftTapArea") { hit.transform.name = "Hit"; } } } 之间的关系,您可以执行此操作:

Page

答案 2 :(得分:0)

以这种方式解决了

页面模型中的

...

    protected $childCount = 0;


    public function pages()
    {
        return $this->hasMany(Page::class, 'owner_id');
    }

    public function childCount()
    {
        return $this->childCount ? $this->childCount : $this->pages()->select('id')->count();
    }
...

我们可以通过$page->childCount()模型方法访问子页数。

答案 3 :(得分:0)

#I found the easiest way to count nested has many relationship counts in laravel:-
    suppose we have three models with has many and nested has many :#
For category Model:-
    public function subCategories()
    {
        return $this->hasMany('App\Models\Subcategory');
    }
For Subcategory Model
    public function products()
    {
        return $this->hasMany('App\Models\Product');
    }


$categories = $this->categoryRepository
            ->with([
                'subCategories' => function ($query) {
                    $query->withCount('products');
                }])
            ->whereIn("id", $categories_id)
            ->orderBy('id', 'desc')->get();
You will get the product count using all these three steps.
Thanks