我对Laravel相当陌生,对如何进行有点困惑。
我有一个角色模型,一个类别模型和一个问题模型。我使用这些数据来显示不同角色类型的测试,按类别分解并显示相关问题。角色有许多类别,类别有许多问题(我创建了数据透视表,并在模型中定义了许多许多关系),但这里棘手的部分是问题也有一个相关的角色(因为不同的角色可以对相同的类别进行类似的测试,但问题不同)。
我开始的方式是首先找到角色:
$role = Role::find(role_id);
然后我得到了相关的分类:
$categories = $role->categories;
然后我循环遍历每个类别并吐出问题:
foreach($r->categories as $cat){
foreach($cat->questions as $cq){
print_r($cq->question);
}
}
但问题是我不知道在哪里设置限制,问题只显示,如果它具有由初始角色id定义的关联角色。
我试过这样做:
foreach($cat->questions()->where('role_id','=',$role_id)->get() as $cq){
print_r($cq->question);
}
但是这个失败了:
Illuminate Database QueryException
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'role_id' in 'where clause' (SQL: select `questions`.*, `category_question`.`category_id` as `pivot_category_id`, `category_question`.`question_id` as `pivot_question_id` from `questions` inner join `category_question` on `questions`.`id` = `category_question`.`question_id` where `category_question`.`category_id` = 1 and `role_id` = 2)
任何帮助都将非常感激!
您需要的是has
。顺便说一下,使用急于(或惰性)加载以避免n+1查询问题。
$role->load('categories'); // lazy load categories, for a single model works just like $role->categories;
$roleId = $role->id;
$role->categories->load(['questions' => function ($q) use ($roleId) {
$q->whereHas('roles', function ($q) use ($roleId) { // assuming roles is relation name
$q->where('roles.id', $roleId); // assuming roles is table name
}]);
// this time you load the relation on the collection so it is completely different
// to calling $category->questions; in a loop
然后你就可以像刚才那样在一个循环中访问问题了。
如果您只需要一个集合中的问题(不附加到类别),那么解决方案将看起来有点不同。