我有以下关系:
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();
我认为我走的是正确的路线,但无法正确使用代码。
答案 0 :(得分: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);
});
});