php - Laravel 查询/访问数据库信息
问题描述
public function countPeople($id = 0, $country = false)
{
if ($id == 0) {
$s = Group::leftJoin('user_hobbies', 'user_hobbies.hobby_id', '=', 'groups.hobby_id')
->where('groups.hobby_id', $this->hobby_id)
->select(DB::raw('count(user_hobbies.user_id) as count'))
->get()
->first();
} else if ($country) {
$s = Group::leftJoin('user_hobbies', 'user_hobbies.hobby_id', '=', 'groups.hobby_id')
->leftJoin('user_locations', 'user_locations.user_id', '=', 'user_hobbies.user_id')
->leftJoin('cities', 'cities.id', '=', 'user_locations.city_id')
->where('groups.hobby_id', $this->hobby_id)
->where('cities.country_id', $country)
->select(DB::raw('count(user_hobbies.user_id) as count'))
->get()
->first();
} else {
$s = Group::leftJoin('user_hobbies', 'user_hobbies.hobby_id', '=', 'groups.hobby_id')
->leftJoin('user_locations', 'user_locations.user_id', '=', 'user_hobbies.user_id')
->where('groups.hobby_id', $this->hobby_id)->where('user_locations.city_id', $id)
->select(DB::raw('count(user_hobbies.user_id) as count'))
->get()
->first();
}
if ($s) {
return $s->count;
}
return 0;
}
初学者在这里..我正在使用其他人的代码来尝试学习/理解一些问题。控制器中存在此功能,用于计算组中的成员,但它不授予该人其他信息的访问权限,例如姓名,照片..等。是否可以从此功能使用相同的功能并返回它作为一种观点?这会让我访问用户信息吗?
我还不太了解如何如此流畅地查询数据库。任何有用的帮助!谢谢你。
解决方案
由于此查询返回一个聚合值(计数),您将无法从中获取任何用户信息。但是,您可以删除->select(DB::raw('count(user_hobbies.user_id) as count'))
最终返回 a 的部分,其中Collection
包含连接表中的所有信息。要从中获得计数,只需使用Collection
'->count()
方法。
$groups = Group::leftJoin('user_hobbies', 'user_hobbies.hobby_id', '=', 'groups.hobby_id')
->where('groups.hobby_id', $this->hobby_id)
->get();
@foreach ($groups as $group)
<p>{{ $group->hobby_id; }}</p>
<p>{{ $group->user_id; }}</p>
@endforeach
<p>Count: {{ $groups->count() }}</p>