这里我看到了一个关于如何实现Instagram
跟随器机制的文档,但这有一些问题,我解决了它们,现在follow
和unfollow
可以正常工作。例如:
Route::get('follow', function () {
$user = User::find(1);
$account = Account::find(2);
$user->follow($account);
});
Route::get('unfollow', function () {
$user = User::find(1);
$account = Account::find(2);
$user->unfollow($account);
});
但这段代码没有得到用户有多少followings
,比如list或count,我试图添加它,但我不能成功地完成
通过这个代码,我可以得到用户的追随者计数:
return $user->withCount(['followers'])->find(1)
或所有用户的追随者列表:
return AppModelsFollower::query()->whereMorphedTo('userable', User::find(1))->get();
Followable
接口:
interface Followable
{
public function followers(): MorphMany;
}
HasFollowed
特性:
trait HasFollowed
{
public function follow(Followable $followable): void
{
if ($this->hasFollowed($followable)) {
return;
}
app(Follower::class)
->user()->associate($this->id)
->userable()->associate($this)
->followable()->associate($followable)
->save();
}
public function unfollow(Followable $followable): void
{
$followable->followers()
->whereMorphedTo('userable', $this)
->delete();
}
public function hasFollowed(Followable $followable): bool
{
if (!$followable->exists) {
return false;
}
return $followable->followers()->whereRelation('user', 'users.id', $this->id)->exists();
}
}
HasFollower
特性:
trait HasFollower
{
public function followers(): MorphMany
{
return $this->morphMany(Follower::class, 'followable');
}
}
Account
模型作为instagram中的用户页面:
class Account extends Model implements Followable
{
use HasFactory, HasFollower;
}
User
型号:
class User extends Authenticatable
{
use HasApiTokens, HasFactory, Notifiable, SoftDeletes, HasFollowed;
public function account(): HasMany
{
return $this->hasMany(Account::class);
}
public function followers(): HasMany
{
return $this->hasMany(Follower::class);
}
public function followings(): HasMany
{
return $this->hasMany(Follower::class);
}
}
followers
迁移:
public function up()
{
Schema::create('followers', function (Blueprint $table) {
$table->id();
$table->foreignId('user_id')->constrained()->cascadeOnDelete()->cascadeOnUpdate();
$table->morphs('userable');
$table->morphs('followable');
$table->timestamps();
});
}
在用户模型中使用trait并实现Followable,而不是手动定义follower和following方法。
class User extends Authenticatable implements Followable
{
use HasApiTokens, HasFactory, Notifiable, SoftDeletes, HasFollower, HasFollowed;
}
在账户模型中也是一样的:
class Account extends Model implements Followable
{
use HasFactory, HasFollower, HasFollowed;
}
Followable
接口:
interface Followable
{
public function followers(): MorphMany;
public function followings(): MorphMany;
}
HasFollower
性状
trait HasFollower
{
public function followers(): MorphMany
{
return $this->morphMany(Follower::class, 'userable');
}
public function followings(): MorphMany
{
return $this->morphMany(Follower::class, 'followable');
}
}
获得追随者和以下列表和计数:
$user = User::with(['followers', 'followings'])->withCount(['followers', 'followings'])->find(1);
$user->followers;
$user->followings;
$user->followers_count;
$user->followings_count;