2017-05-19 32 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

追隨者許多對一個藝術家和追隨者許多對一個用戶 –