Laravel如何通过用户ID获取计数跟随者?

时间:2017-05-19 06:36:17

标签: 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_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
    }
  ]

如果我使用 - >其中(' followers.user_id',$ userId)的结果只会获得followers: 1

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

谢谢!

2 个答案:

答案 0 :(得分:1)

<强> EDITED

这是一对多关系。你要做的是

模特艺术家

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

中的

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

答案 1 :(得分:0)

这是我的表结构

 1. users
  - id 
  - name

2. follower
  - id
  -user_id
  -artist_id

3. artists
  -id
  -name
  -src

感谢您的帮助