用户模型:
public function followers() {
return $this->hasMany('Follower', 'f_who');
}
配置文件控制器:
$user_followers = User::with('followers')->find($user_id)->toArray();
结果
Array
(
[user_id] => 1
[username] => dev
[email] => dev@dev.com
[name] => AdminName
[surname] => AdminSur
[profile_image] => /img/anon1.jpg
[ip] => 127.0.0.1
[pp] => 0
[np] => 0
[followers_count] => 2
[photos_count] => 0
[created_at] => 2014-12-17 12:08:04
[updated_at] => 2015-01-18 21:15:55
[followers] => Array
(
[0] => Array
(
[follower_id] => 1
[f_who] => 1
[f_which] => 2
[created_at] => -0001-11-30 00:00:00
[updated_at] => -0001-11-30 00:00:00
)
[1] => Array
(
[follower_id] => 2
[f_who] => 1
[f_which] => 3
[created_at] => -0001-11-30 00:00:00
[updated_at] => -0001-11-30 00:00:00
)
)
)
我需要使用关系在子“followers”数组中获取关注者姓名,姓氏等(左连接用户表)。我真的很困惑这种关系。如果问题或结构不清楚,请告诉我,我会尝试解决这个问题。
f_who - 表示被关注的人。
f_which - 关注的人
如果我尝试像这样的belongsToMany关系:
public function followers() {
return $this->belongsToMany('Follower', 'users')->withPivot('f_who');
}
我明白了:
Unknown column 'users.follower_id' in 'field list' (SQL: select `followers`.*, `users`.`user_id` as `pivot_user_id`, `users`.`follower_id` as `pivot_follower_id`, `users`.`f_who` as `pivot_f_who` from `followers` inner join `users` on `followers`.`follower_id` = `users`.`follower_id` where `users`.`user_id` in (1))
应选择users
。user_id`
答案 0 :(得分:1)
是其他用户的关注者?如果是这样,那么只需将用户与用户联系起来。
在您的用户模型中创建一个方法,如此。
class User {
public function followers() {
// Model, pivot table, id of person being followed, id of person following
return $this->belongsToMany('User', 'followers', 'f_who', 'f_which');
}
}
查询关系
$user = User::with('followers')->find($user_id)->toArray();