【问题标题】:Laravel 5 RelationsLaravel 5 关系
【发布时间】:2025-12-01 20:35:02
【问题描述】:

数据库结构:

-用户表 -用户身份 -姓名 -...

-跟随表格 -用户身份 -follow_id

所以当用户关注另一个时,它将被插入到关注表中

以及何时获得用户关注

 $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');

}

并通过这种关系在跟随模型方面

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

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

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

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

【问题讨论】:

  • 我假设follow_idusers 表中的一个ID
  • 是的,所以我想通过这个 id 获取用户信息

标签: php laravel laravel-5 eloquent laravel-5.1


【解决方案1】:

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

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

其次,这不是必需的,只需将users 表中的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 表的模型。

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

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-manyhttp://laravel.com/docs/5.1/eloquent

希望这会有所帮助!

【讨论】: