【问题标题】:How i run loop for laravel recursive relationship我如何为 laravel 递归关系运行循环
【发布时间】:2021-09-05 23:35:44
【问题描述】:

This is comments table

这是我的 laravel 关系 -

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

public function allChildren()
{
    return $this->children()->with('allChildren');
}

如何为此运行递归 foreach 循环,以便打印 cmets 的 cmets。

【问题讨论】:

    标签: php laravel relationship


    【解决方案1】:

    您知道关系作业是为了方便您准备正在运行的查询。

    如果在准备过程中无限循环,查询将永远不会开始运行。

    在某些时候,您必须选择需要恢复的级别。

    以 4 级为例:

    Post::with('comments.children.children.children').get();
    

    【讨论】:

    • 但我需要像 instagram 这样没有级别限制的循环
    • @Ranveer Instagram 使用 Javascript 来实现。无限滚动,而不是无限查询。有一些解决方案可以通过让所有 cmets(无论他们的级别)都有一个相关帖子的外键来获取帖子的所有 cmets(使用Post::with('comments') 获取它们,然后将结果重新排序为带有父级的层次结构/通过代码的儿童 cmets。
    猜你喜欢
    • 1970-01-01
    • 2014-12-26
    • 1970-01-01
    • 2019-09-15
    • 2016-07-18
    • 1970-01-01
    • 2022-01-21
    • 2013-10-23
    • 1970-01-01
    相关资源
    最近更新 更多