【问题标题】:Laravel - Hierarchy in Eloquent modelLaravel - Eloquent 模型中的层次结构
【发布时间】:2013-07-31 21:58:55
【问题描述】:

我的数据库有这个层次结构:

- Manager:
  - Coordinator:
    - Supervisor:
      - Operator

这段代码,输出所有“coordinator”属于“manager”:

Manager::find(1)->coordinator()->get();

可以直接让所有“主管”属于“协调员”吗?示例:

Manager::find(1)->coordinator()->supervisor()->get();

对不起,我是巴西人

【问题讨论】:

  • 是的,你可能只需要定义所有的关系。

标签: laravel laravel-4 hierarchy eloquent


【解决方案1】:

这是完全可能的,您只需要在模型中定义所有关系。然后,您可以通过以下方式检索特定“经理”的所有“操作员”:

Manager::find(1)->coordinator->supervisor->operator;

在该代码中,我使用了 Eloquent ORM 附带的动态属性。

当我说“您需要定义模型中的所有关系”时,请执行以下操作:

class Manager extends Eloquent
{
    public function coordinator()
    {
        return $this->hasMany('Coordinator');
    }
}

然后你会为有很多supervisor的coordinator和有很多operator的supervisor做同样的事情。

请参阅有关 Relationship, one-to-many, in Laravel 4 的文档。

【讨论】:

  • 我已经这样做了,但返回:未定义属性:Illuminate\Database\Eloquent\Collection::$supervisor
  • 去掉美元符号。
  • 发现“错误”,返回一个 Collection -Illuminate\Database\Eloquent\Collection - add ->first() 或循环工作!!谢谢
猜你喜欢
  • 1970-01-01
  • 2013-05-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-05-01
  • 1970-01-01
  • 1970-01-01
  • 2015-01-26
相关资源
最近更新 更多