【问题标题】:Laravel how to get count follower by user id?Laravel如何通过用户ID获取关注者数量?
【发布时间】:2017-10-19 04:04:26
【问题描述】:

我下面有 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);
}

我想得到 Result 如下

 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) by result 将只得到followers: 1

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

谢谢!

【问题讨论】:

  • 当我登录时,我想获取我关注的艺术家,并且每个艺术家显示关注者总数
  • 如果我使用这个函数 ->where('followers.user_id',1) 我无法获得关注者结果计数只有 1 为什么?
  • 为什么不使用关系而不是硬编码呢?
  • 对不起,你的意思是关系而不是硬编码?

标签: php jquery mysql laravel laravel-5


【解决方案1】:

已编辑

这是一个多对多的关系......你要做的是

模特艺术家

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

这将返回一个数据数组,如

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

【讨论】:

  • 感谢帮助!您能帮忙更改如何通过 user_id 获取艺术家吗?
  • 在我的数据库中,我关注了 3 位艺术家,但我只得到了 1 位艺术家结果
  • 我可以看看你的数据库结构吗?
  • 我有表:1.users 2.Artists 3.Follower
  • 希望你能帮上忙
【解决方案2】:

这是我的表结构

 1. users
  - id 
  - name

2. follower
  - id
  -user_id
  -artist_id

3. artists
  -id
  -name
  -src

感谢您的帮助

【讨论】:

  • 关注者与艺术家相关,与用户相关。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-03-24
  • 1970-01-01
  • 2019-08-22
  • 2013-06-30
相关资源
最近更新 更多