Laravel 5 关系

Laravel 5 Relations

数据库结构:

-用户Table -user_id -姓名 -...

-关注Table -user_id -follow_id

所以当用户关注另一个人时,它将被插入关注 table

以及何时获得用户关注者

 $user  = User::where('user_id',$id)->first();


    $user['followers'] = $user->Followers;
    $user['following'] = $user->Following;

return $user;

通过用户模型端的这个关系

public function Followers()
{
    return $this->hasMany('App\Follow','follow_id','user_id');

}

并通过这个关系在Follow Model端

public function getUserData()
    {
    return $this->belongsTo('App\User','user_id','user_id');
   }

它对我来说很好用,它给了我每一个 id 但问题是

我想获取有关从该关系返回的每个用户的信息

所以我应该为每个返回的用户调用用户模型以获取他的信息 还是什么??

您建立多对多关系的方式几乎是正确的。

首先,将 Followers() 方法更改为 followers(),因为 Laravel 遵循 PSR-2 标准。

其次,这不是必需的,但将 users table 中的 user_id 列更改为 id。这是一个不需要遵循的 laravel 约定,但是,在这一点上,我认为没有任何理由不遵循它。我假设你有类似的东西:

protected $primaryKey = 'user_id';

在您的 User 模型中。如果您将 user_id 列更改为 id,您将不再需要上述声明。 (如果您没有该行并且想继续使用 user_id 作为主键,您将必须将该行添加到您的 User 模型中。

第三,将followers()中的关系类型更改为:

public function followers()
{
    return $this->belongsToMany('App\User', 'follower', 'user_id', 'follow_id'); 
    //follower is the table name, user_id is column that relates to the current model and follow_id is the column that is for the relationships
}

完成上述所有操作后,您现在可以通过以下操作获得拥有所有关注者的用户:

$user = User::with('followers')->find($id);

这将使您只需执行以下操作即可获得关注者:

$user->followers

此时你不能摆脱你的 Follow 模型,因为你通常不需要 pivot table.

的模型

要获得以下关系,只需添加:

public function following()
{
    return $this->belongsToMany('App\User', 'follower', 'follow_id', 'user'); 
}

到您的 User 模型。

要再次访问此内容,您可以:

$user = User::with('following')->find($id);

or if you have already have the user model and the relationship isn't loaded you can:

$user->load('following'); //in this case following is the name of the method where you have declared the relationship.

更多信息请参考文档http://laravel.com/docs/5.1/eloquent-relationships#many-to-many and http://laravel.com/docs/5.1/eloquent

希望对您有所帮助!