【问题标题】:Laravel recursive relations and returning $thisLaravel 递归关系并返回 $this
【发布时间】:2018-07-05 01:22:06
【问题描述】:

我的导航栏具有未知行业级别,其中可能有子行业,我想编写递归关系以获取顶部并将其显示为类别。我试过这个:

public function category()
{
    if($this->parent_id == 0){
        return $this;
    } else {
        $this->parent_industry->category();
    }
}

但我不断得到 LogicException:关系方法必须返回 Illuminate\Database\Eloquent\Relations\Relation 类型的对象

如何写递归关系并返回$this

【问题讨论】:

  • 你可以尝试在同一个模型中创建关系。我假设像一张办公桌,你会在表格中拥有像employee_id和manager_id这样的东西,所以你可以在office模型中为belongsTo编写2个函数和 hasMany() 这可能有效(我在 Rails 中做过类似的事情,它有效,这也可能在 Laravel 中有效)
  • 如果你像这样调用函数:$var->category(); 而不是作为属性$var->category;,它应该像现在一样工作。

标签: php laravel recursion relationship


【解决方案1】:

您好,您可以轻松完成此操作,而不是使用 while

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

public function parent()
{
   return $this->belongsTo('App\MenuItem', 'parent_id');
}

public function root()
{
    if ($this->parent)
        return $this->parent->root();

    return $this;
}

使用递归就简单多了。

希望这会有所帮助。

【讨论】:

    【解决方案2】:

    试试这个关系:

    public function children()
    {
        return $this->hasMany('App\MenuItem', 'parent_id');
    }
    
    public function parent()
    {
        return $this->belongsTo('App\MenuItem', 'parent_id');
    }
    
    public function getRoot()
    {
        $cur = $this;
        while ($cur->parent) {
            $cur = $cur->parent;
        }
        return $cur;
    }
    

    【讨论】:

      猜你喜欢
      • 2014-12-26
      • 1970-01-01
      • 2021-05-20
      • 2022-01-21
      • 2020-06-12
      • 2020-07-31
      • 2014-08-21
      • 2016-06-21
      相关资源
      最近更新 更多