【问题标题】:Make a users list like instagram制作一个像 instagram 这样的用户列表
【发布时间】:2018-12-16 21:47:54
【问题描述】:

请帮忙..
我有 2 张桌子 当前用户 ID = 3 用户表:

|  user_id  |      email       |   name   |
-------------------------------------------
|     1     |   one@gmail.com  |  ridwan  |
|     2     |   two@gmail.com  |   budi   |
|     3     |   six@gmail.com  |  stevan  |
|     4     |   ten@gmail.com  |  agung   |

关系表 [user_id 和 follower_id 与用户表相关]

|  relation_id  | user_id | follower_id | 
----------------------------------------- 
|       1       |    1    |      3      | 
|       2       |    2    |      3      | 

我想获取用户列表,但如果我已经与用户有关系,它会给我一个“关注”状态,就像 instagram 一样,可能看起来像这样

{
    user_id : 1,
    name    : ridwan,
    status  : following
},
{
    user_id : 2,
    name    : budi,
    status  : following
},
{
    user_id : 4,
    name    : agung,
    status  : not following
}

我如何在 laravel 中做到这一点?

谢谢你..

【问题讨论】:

  • 也许this 可以帮助你。您必须在模型中定义关系,然后您可以通过设置正确的resources 来检索它们。

标签: mysql laravel eloquent relationship lumen


【解决方案1】:

在您的关系模型中

public function user()
{
    return $this->belongsTo(User::class);
}

然后,在您的控制器中(您想要获取此列表的位置),您只需要使用 Eloquent 或 Query Builder 来获取您想要的内容(使用即时加载,它总是更好):

//get all users related to your_current_user
$relations = Relation::where('follower_id', your_current_user_id)->with('user')->get(); 

最后,您只需按照自己的意愿操作数据,例如:

foreach($relations as $relation){
    $relation->user->name; //get the name of the related user
}

看看Relationships

【讨论】:

    【解决方案2】:

    谢谢你们.. 最后我使用 sql 案例,我只是对如何获取具有“关注”状态的数据感到困惑

    代码如下:

    DB::table('users')->leftjoin('relationships', 'users.user_id', '=', 'relationships.user_id')->select('users.user_id','users.status as user_type','users.email','users.display_name','users.profile_image',DB::raw('(CASE WHEN relationships.follower_id = ' . $user_id . ' THEN "Following" ELSE "Not Following" END) AS status'))->orderBy('user_id','asc')->where('users.user_id','!=',$user_id)->get();
    

    【讨论】:

      猜你喜欢
      • 2013-02-20
      • 1970-01-01
      • 2020-08-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多