关注的逻辑
在 Aufree 关注了 Summer 之后,Aufree 将成为 Summer 的粉丝,Summer 为 Aufree 的关注用户;在 Aufree 取消关注 Summer 之后,Summer 将从 Aufree 的关注人列表中被移除,Aufree 则从 Summer 的粉丝列表中被移除。
由此可见,在关注用户功能的整个流程中,最重要的两个主体分别是被关注的用户(user_id)和粉丝(follower_id),我们可以通过被关注用户(user_id)来获取到他所有的粉丝,也能通过一个粉丝(follower_id)来获取到他关注的所有用户。
创建粉丝表迁移文件
我们可以通过创建一个粉丝表来存放用户对应关注的所有粉丝。
我们需要为粉丝关系表生成一个迁移文件。
$ php artisan make:migration create_followers_table --create="followers"
并在该迁移文件中增加两个字段 user_id 和 follower_id 用于接下来的操作。
database/migrations/[timestamp]_create_followers_table.php
increments('id');
$table->integer('user_id')->index();
$table->integer('follower_id')->index();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('followers');
}
}
在获取用户的关注人列表和粉丝列表时需要用到 user_id 和 follower_id 字段进行数据查找,因此我们需要为其增加索引,以便提高查询效率。
执行新建的迁移文件。
$ php artisan migrate
修改用户模型
一个用户(粉丝)能够关注多个人,而被关注者能够拥有多个粉丝,像这种关系我们称之为「多对多关系」。
在 Laravel 中我们使用 belongsToMany 来关联模型之间的多对多关系。以粉丝为例,一个用户能够拥有多个粉丝,因此我们在用户模型中可以像这样定义:
public function followers()
{
return $this->belongsToMany(User::Class);
}
在 Laravel 中会默认将两个关联模型的名称进行合并并按照字母排序,因此我们生成的关联关系表名称会是 followers_user。我们也可以自定义生成的名称,把关联表名改为 followers。
public function followers()
{
return $this->belongsToMany(User::Class, 'followers');
}
除了自定义合并数据表的名称,我们也可以通过传递额外参数至 belongsToMany 方法来自定义数据表里的字段名称。如下:
public function followers()
{
return $this->belongsToMany(User::Class, 'followers', 'user_id', 'follower_id');
}
belongsToMany 方法的第三个参数 user_id 是定义在关联中的模型外键名,而第四个参数 follower_id 则是要合并的模型外键名。
最终我们在用户模型中定义的关联如下:
app/Models/User.php
belongsToMany(User::Class, 'followers', 'user_id', 'follower_id');
}
public function followings()
{
return $this->belongsToMany(User::Class, 'followers', 'follower_id', 'user_id');
}
}
我们可以通过 followers 来获取粉丝关系列表,如:
$user->followers();
通过 followings 来获取用户关注人列表,如:
$user->followings();