提问者:小点点

使用雄辩的关系通过关系和特定参数检索模型


我一直在努力将以下查询转换为雄辩的:

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;

这些关系定义如下:

  • 用户自备口香糖诱导剂

现在我的功能如下:

/**
* 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个答案

匿名用户

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

$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;
        }
    }
}