【问题标题】:Laravel Get all child node count with conditionLaravel 根据条件获取所有子节点数
【发布时间】:2015-11-12 19:33:53
【问题描述】:

我在我的应用程序中使用Laravel5.1。在这个我有一个表名用户和用户表的架构如下。

id          Name         Parane_id     Node
1           ABC          0             
2           XYZ          1              L
3           DFS          1              R
4           GJK          2              L
5           DSG          3              L
6           FAF          4              R
7           KES          2              R  

我想计算用户 1 左侧的所有用户(即 2、4、6、7)所以计数为 4。

就像我想要 2 的右侧一样,那么它将返回 7,因此计数为 1。

这怎么可能使用Laravel Eloquent

非常感谢任何帮助。

【问题讨论】:

  • “用户 1 的所有用户左侧”是什么意思?
  • 你能提供更多关于左侧和右侧的解释吗?
  • @mdamia 就像每个人都有两条腿一样,一条在左,另一条在右,所以如果我有孩子,我会将它们添加为左或右。所以基本上每个父母最多有两个孩子,孩子有子孩子,依此类推。所以在我的示例中,您可以看到用户 ABC 有两个孩子 2,3,其中 XYZ 位于左侧(节点:L 表示左侧,R 表示右侧),DFS 位于右侧。希望你能得到它,如果没有,请让我。
  • 更多了解请查看图片imgur.com/01JRusx

标签: php mysql eloquent laravel-5.1


【解决方案1】:

你想在特定条件下计算你的树节点,在这种情况下是节点的左子节点。

为您的User 定义子代。然后创建一个函数来遍历您的子树并进行计数。

class User extends Model {

    public function children()
    {
        return $this->hasMany('App\User', 'parent_id');
    }

    public function countChildren($node = null)
    {
        $query = $this->children();
        if (!empty($node))
        {
            $query = $query->where('node', $node);
        }

        $count = 0;
        foreach ($query->get() as $child)
        {
            $count += $child->countChildren() + 1; // Plus 1 to count the direct child
        }
        return $count;
    }

}

统计用户 id 1 的左孩子。

$user = User::find(1);
$count = $user->countChildren('L');

【讨论】:

  • 有没有更好的方法来统计laravel中的孩子?
猜你喜欢
  • 1970-01-01
  • 2012-07-13
  • 2014-08-21
  • 1970-01-01
  • 2018-02-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多