仅供参考,我使用的是Laravel 5.
我有两张桌子
users
id
first name
skills
id
name
和数据透视表
skill_user
skill_id
user_id
如果我在MySQL中选择如下:
select users.id as id, users.first_name, skills.name from users
left join skill_user on users.id = skill_user.user_id
left join skills on skill_user.skill_id=skills.id
我明白了:
id, first_name, skill
1, Jenna, Reliable
1, Jenna, Organized
2, Alex, Hardworking
3, Barry, Capable
3, Barry, Amiable
3, Barry, Patient
4, Janine, (null)
我通过Controller将其传递给视图:
$peoples = [];
$peoples = \DB::table('users')
->select(\DB::raw('users.id as id, first_name, skill.name as name"'))
->leftJoin('skill_user','users.id','=','skill_user.user_id')
->leftJoin('skills','skill_user.skill_id','=','skills.id')
->get();
return view('find-people', compact(['peoples']));
现在,我想在视图中循环这个(伪代码):
forelse ( peoples as people )
people - > first_name
people - > skill
empty
no people found
endforelse
在某种意义上哪一项都很好 - 但是当有多种技能时,名字会重复。
我可能会通过比较user_id与自身进行比较来破解技能循环,但这似乎是一种笨拙的方式。
user_id = $peoples->id
while (some looping criteria)
{
write out skills
if($peoples->id != user_id){break;}
}
如何以优雅/雄辩的方式遍历记录集?或者还有一个更好的完全做到这一点?
答案 0 :(得分:1)
如果在模型中定义关系,则无需尝试构建原始SQL来实现该目标。这就是Laravel ORM“Eloquent”的用途!
class People extends Model {
public function skills () {
return $this->hasMany('Skill');
}
}
然后定义技能模型:
class Skill extends Model {
public function People () {
return $this->belongsToMany('People');
}
}
现在,您可以遍历People
模型并为每个人获取->skills
。这样您就不会遇到正在遇到的重复问题,并且通过利用ORM大大简化了您尝试实现的SQL。