请帮助。
我有2张桌子
当前user_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与Users表相关]
| 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中做到这一点?
谢谢..
答案 0 :(得分:0)
在您的关系模型中
at RUBY.concateRule(<script>:15)
at RUBY.block in (root)(<script>:43)
at org.jruby.RubyHash.each(org/jruby/RubyHash.java:1350)
at RUBY.block in (root)(<script>:40)
at org.jruby.RubyArray.each(org/jruby/RubyArray.java:1735)
at RUBY.block in (root)(<script>:39)
at org.jruby.RubyArray.each(org/jruby/RubyArray.java:1735)
at RUBY.<main>(<script>:38)
然后,在您的控制器中(您想要获取此列表的地方),您只需要使用Eloquent或Query Builder即可获取所需的内容(渴望加载,总会更好):
public function user()
{
return $this->belongsTo(User::class);
}
最后,您只需要根据需要操作数据即可,例如:
//get all users related to your_current_user
$relations = Relation::where('follower_id', your_current_user_id)->with('user')->get();
答案 1 :(得分:0)
谢谢大家..最终我使用了sql case,我只是在困惑如何获取具有'following'状态的数据
这是代码。
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();