2017-07-12 103 views
0

我有以下表Laravel 5. * - 雄辩的多对多关系

USERS = username | email | name 
FOLLOWERS = user_id | follower_id 

当登录用户点击“跟随”我的代码,节省了他的身份证内followers.follower_id,以及用户的ID谁他想跟着保存在followers.user_id里面。

要查看用户有多少关注者以及有多少用户一个用户下使用:

$followers = Follower::where('user_id', $user->id)->count(); 
$following = Follower::where('follower_id', $user->id)->count(); 

这个效果很好,但我想,以显示有关一个用户的追随者信息。我已经试过如下:

$first_follower = $followers[0]->user->username; 

但它返回用户未遵循的追随者。

我想知道我怎样才能得到关于跟随信息

用户模型

protected $fillable = ['username','email','name']; 

public function follow() { 
    return $this->hasMany('Shop\Follower');  
} 

跟随模式

protected $fillable = ['user_id','follower_id']; 

public function user() { 
    return $this->belongsTo('Shop\User'); 
} 
+0

你应该使用多对多的关系来克服这个 –

回答

0

如果我得到这个权利的追随者实例User类/模型,所以你不需要一个Follower模型。你可以只定义Many To Many Relationship

在您的用户模型,你可以添加:

public function followers() 
{ 
    return $this->belongsToMany('Shop\User', 'followers', 'user_id ', 'follower_id'); 
} 

public function following() 
{ 
    return $this->belongsToMany('Shop\User', 'followers', 'follower_id', 'user_id'); 
} 

比你能仅仅通过$user->followers访问用户的关注,这将返回一个Laravel Collection$user->following您可以访问那些在用户正在关注。

//Get the count of all followers for $user 
$count = $user->followers()->count(); 

//Get the count of all followed by $user 
$count = $user->following()->count(); 

//Get the username of the first follower 
$follower = $user->followers()->first(); 
echo $follower->username; 

//Loop trough all followers 
foreach ($user->followers as $follower) { 
    echo $follower->username; 
} 

定义这种关系可以帮助您节省/删除追随者只是使用attach()detach()方法

// The $user will be followed by an user with $followerId 
// A record in the `followers` table will be created with 
// user_id = $user->id and follower_id = $followerId 
$user->followers()->attach($followerId); 

// The $user will stop be followed by an user with $followerId 
$user->followers()->detach($followerId); 

一个侧面说明: 有调用followers()方法和调用之间的差异followers属性。首先将返回BelongsToMany关系,你可以调用其上的所有雄辩查询生成器方法和以后将返回Collection

/** @var Illuminate\Support\Collection */ 
$user->followers; 

/** @var Illuminate\Database\Eloquent\Relations\BelongsToMany */ 
$user->followers(); 
0

你应该如何实现关系的一个例子,是上面。许多用户通过关注者表提供了许多用户。你可能不需要跟随者模型,因为你已经有了一个用户模型。您的代码将工作经过一番分析和改进,但我会强烈建议更换你做出这样的事情inuser模型来代替:

public function followers() { return $this->belongsToMany('App\User','followers','user_id','follower_id'); } public function following_users() { return $this->belongsToMany('App\User','followers','follower_id','user_id'); }

比你可以访问的追随者$user->followers(这将返回雄辩收集和你将能够根据laravel docs collection api)和某个像$user->followers[0]

希望我能得到你的答案。