Php Laravel如何通过用户id获得计数跟随者?
我有下面的laravel jqueryPhp Laravel如何通过用户id获得计数跟随者?,php,jquery,mysql,laravel,laravel-5,Php,Jquery,Mysql,Laravel,Laravel 5,我有下面的laravel jquery public function getFollower(Request $request){ $userId = $request->get('user_id'); $artists = DB::table('artists') ->select('artists.id', 'artists.title as name ','artists.src as poster','followers.user_
public function getFollower(Request $request){
$userId = $request->get('user_id');
$artists = DB::table('artists')
->select('artists.id', 'artists.title as name ','artists.src as poster','followers.user_id',DB::raw('COUNT(followers.user_id) as followers'))
->leftjoin('followers', 'artists.id','=', 'followers.artist_id')
->where('artists.status',0)
->groupBy('followers.artist_id')
->orderBy('followers.id', 'desc')
->get();
return Response()->json(['data' => $artists], 200);
}
我想得到如下结果
data: [
{
"id": 3,
"name ": "Artist 3",
"poster": "",
"user_id": 1,
"followers": 1
},
{
"id": 2,
"name ": "Hello Artist 2",
"poster": "",
"user_id": 1,
"followers": 1
},
{
"id": 1,
"name ": "Thai",
"poster": "",
"user_id": 3,
"followers": 10
}
]
如果我按结果使用->where('followers.user_id',$userId),将只获得followers:1
任何人都可以帮助我如何获得上述结果,我可以使用->where('followers.user\u id',$userId)
谢谢 已编辑 这是一种多对多的关系。。你要做的是 模特艺术家
protected $appends = ['followers_count'];
public function followers()
{
return $this->belongsToMany('App\User','follower','artist_id','user_id');
}
public function getFollowersCountAttribute()
{
return count($this->followers);
}
模型用户
protected $appends = ['followed_count'];
public function artists()
{
return $this->belongsToMany('App\Artist','follower','user_id','artist_id');
}
public function getFollowedCountAttribute()
{
return count($this->artists);
}
public function getArtists(Request $request)
{
$user_id = $request->get('user_id');
// get the user using the user_id
$follower = User::with('artists')->find($user_id);
return response()->json(['data' => $follower ], 200);
}
在您的控制器中
protected $appends = ['followed_count'];
public function artists()
{
return $this->belongsToMany('App\Artist','follower','user_id','artist_id');
}
public function getFollowedCountAttribute()
{
return count($this->artists);
}
public function getArtists(Request $request)
{
$user_id = $request->get('user_id');
// get the user using the user_id
$follower = User::with('artists')->find($user_id);
return response()->json(['data' => $follower ], 200);
}
这将返回一个数据数组,如
这是我的桌子结构
1. users
- id
- name
2. follower
- id
-user_id
-artist_id
3. artists
-id
-name
-src
感谢您的帮助当我登录时,我想获取我跟踪他们的艺术家以及每个艺术家秀的总粉丝数如果我使用此函数->where('followers.user_id',1)我无法获取粉丝结果计数,仅1为什么?为什么不使用关系而不是硬编码?抱歉,什么是关系而不是硬编码?谢谢你的帮助!你能帮我改变一下如何按用户id获取艺术家吗?在我的数据库中,我跟踪了3位艺术家,但我只得到了1位艺术家的结果。我可以看到你数据库的结构吗?我有表:1.users 2.Artists 3.FollowerI我希望你能帮助与艺术家和用户相关的追随者。