【问题标题】:Laravel Eloquent - method to obtain 'grandchildren' where grandparent_id matchesLaravel Eloquent - 获取祖父母 ID 匹配的“孙子”的方法
【发布时间】:2016-11-07 16:54:29
【问题描述】:

我有以下关系:

Tool:
-----
id
name
description


Competency:
-----------
id
name
description
tool_id


Indicator:
----------
id
name
description
competency_id

我正在尝试获取直接属于指定工具的所有指标(即孙子)。关系是工具有很多能力,能力有很多指标。

到目前为止,我的()代码是:

hasManyThrough('Indicator', 'Competency', 'tool_id', 'competency_id')->where('tool_id', '=', 1)->get();

我认为我的思路是正确的,但无法正确编写代码。

【问题讨论】:

  • 我想你想告诉“工具有很多能力,能力有很多指标(不是工具)”不是吗?
  • 是的,我的错误。我会更新这个

标签: laravel orm eloquent


【解决方案1】:

获取指定能力的指标。

$indicatorsOfCompetency = Indicator::where("competendy_id", $yourCompetencyID)->get();

或者,取决于你的 laravel 关系名称

$competency = Competency::find($yourCompetencyID);

$indicatorsOfCompetency = $competency->indicators()->select(["id","field1","field2"]);


当他的能力与指示的工具相关时获取指标。

// Note: Depending of your Laravel version, could be "lists" or "pluck" function.
$competencyIDS = Competency::where("tool_id", $yourToolID)->lists("id");

$indicators = Indicator::whereIn("competency_id", $competencyIDS);

或更多雄辩,使用whereHas()

$indicators = Indicator::whereHas("competency", function($qCompetency) use ($yourToolID){
    $qCompetency->whereHas("tools", function($qTool) use($yourToolID){
        $qTool->where("id", $yourToolID);
    });
});

【讨论】:

  • 我们正在尝试传入 tool_id 并仅过滤直接位于其下方的指标,而忽略能力。由于我们没有引用任何能力 ID,上述内容如何允许我们这样做?
猜你喜欢
  • 1970-01-01
  • 2013-06-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-09-04
  • 2016-01-04
相关资源
最近更新 更多