使用Eloquent Relationships通过关系和特定参数检索模型

时间:2014-06-04 14:51:40

标签: laravel eloquent relationships

我一直在努力尝试将以下查询转换为Eloquent:

SELECT * FROM induction_modules INNER JOIN inductions ON induction_modules.induction_id = inductions.id INNER JOIN induction_user ON induction_user.induction_id = inductions.id WHERE induction_user.user_id = 1 AND induction_modules.id = 56;

关系定义如下:

  • 用户所属的移动感应
  • 感应所属的移动用户
  • InductionModule属于归纳(与hasOne相反)
  • InductionModuleItem属于InductionModule(与hasOne相反)。

现在我的功能如下:

/**
* Find specific induction module of user
*
* @param int $id
* @param int $inductionModuleID
* @param array $with
* @return Illuminate\Database\Eloquent\Model|null
*/
public function inductionModule($id, $inductionModuleID, $with = array())
{
    $user = $this->find($id);

    if ($user)
    {
          return /* HOW DO I GET THE MODULE WITH ITS ITEMS?? */
    }

    return null;
}

理想情况下,我想做什么:

$inductionModule = $user->inductions()->modules()->with('items)->WHEREMODULEID=56.

感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

这对你有用,但我还没有测试过。

$user = User::with(array('inductions.modules.items' => function($q)
{
    $q->where('induction_modules.id', 56);      
}))->find(1);

foreach($user->inductions as $induction) {
    // echo $induction->description;
    foreach($induction->modules as $module) {
        // echo $module->description;
        foreach($module->items as $item) {
            // echo $item->description;
        }
    }
}