2017-05-19 25 views
1

我有以下Laravel如何通过用户ID获得计数跟随者?

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 
    } 
    ] 

如果我使用jQuery的laravel - >在哪里( 'followers.user_id',$用户id)的结果将得到followers: 1只有

任何人都可以帮助我,我怎样才能得到结果如上,我可以使用->where('followers.user_id',$userId)

谢谢!

+0

当我登录我想要得到艺术家,我跟着他们和每个艺术家显示计数总追随者 –

+0

如果我使用此func - > where('followers.user_id',1)我无法获得追随者结果数只有1为什么? –

+0

为什么不使用关系而不是硬编码呢? – Demonyowh

回答

1

EDITED

这是一个多对多的关系..你会做什么是

MODEL艺术家

protected $appends = ['followers_count']; 

public function followers() 
{ 
    return $this->belongsToMany('App\User','follower','artist_id','user_id'); 
} 

public function getFollowersCountAttribute() 
{ 
    return count($this->followers); 
} 

模型USER

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

这将返回数据的数组一样

{ 
    id: 1, 
    name:'You', 
    followed_count: 2, 
    artists: [ 
     { 
      id:1, 
      name: 'Demonyowh', 
      follower_count: 9999, 
     }, 
     { 
      id:5, 
      name: 'Brian', 
      follower_count: 9999, 
     }, 
    ], 
} 
+0

感谢您的帮助!你能帮助改变我怎么才能通过user_id获得艺术家? –

+0

ofcouse ..看我编辑一段时间后 – Demonyowh

+0

在我的数据库中,我跟着3艺术家,但我只得到1艺术家的结果 –

0

这里是我的表结构

1. users 
    - id 
    - name 

2. follower 
    - id 
    -user_id 
    -artist_id 

3. artists 
    -id 
    -name 
    -src 

谢谢你帮助

+0

请向我解释他们之间的关系。 – Demonyowh

+0

关注艺术家和与用户相关的关注者。 –

+0

追随者许多对一个艺术家和追随者许多对一个用户 –