laravel - laravel中的传入和传出好友请求
问题描述
我想在我的 laravel 应用程序中创建友谊系统,所以我需要加载所有用户(传入请求、传出请求和其他新用户)为此我的控制器是这样的
$users = User::with([
'friendships' => function ($query) {
$query->where('sender_id', Auth::id());
}
])
->where('users.id', '!=', Auth::id())
->get();
我的观点
@foreach($records as $i=>$all_user)
<tr>
<td>{{++$i}}</td>
<td>{{$all_user['name']}}</td>
<td>{{$all_user['email']}}</td>
@forelse($all_user['friendships'] as $req_status)
<td><a href="{{ url('/send_req') }}/{{$all_user->id}}" class="btn btn-success">{{$req_status->status}}</a></td>
@empty
<td><a href="{{ url('/send_req') }}/{{$all_user->id}}" class="btn btn-primary">send Req</a></td>
@endforelse
</tr>
@endforeach
但是这段代码有很多缺陷。我得到了除登录用户之外的所有用户,但没有传入请求的记录。因此,如果用户有任何传入请求,那么我认为应该更改状态
我的用户模型是这样的
function friendships()
{
return $this->hasMany('App\Friendship','recipient_id','id');
}
友谊表是
Schema::create(config('acquaintances.tables.friendships'), function (Blueprint $table) {
$table->id();
$table->morphs('sender');
$table->morphs('recipient');
$table->string('status')->default('pending')->comment('pending/accepted/denied/blocked/');
$table->timestamps();
});
解决方案
有一个包可以帮助您轻松地在 laravel 中建立一个友谊系统,就像我 个人没有使用它一样,我在我的一个投资组合项目中做了一个跟随系统,在这里也有一个请求接受系统
我建议您手动尝试的是接近此的东西。
用户模型的友好特征
public function sentRequests()
{
return $this->belongsToMany('App\User', 'friendships', 'user_id', 'friend_id');
}
public function recievedRequests()
{
return $this->belongsToMany('App\User', 'friendships', 'friend_id', 'user_id');
}
public function friends()
{
$sentAccepted = $this->sentRequests()->wherePivot('accepted', true)->get();
$recievedAccepted = ->$this->friendOf()->wherePivot('accepted', true)->get();
return $sentAccepted->merge($recievedAccepted);
}
public sendRequest(User $user){
$this->sendRequests()->create(['friend_id' , $user->id]);
}
public acceptRequest(User $user){
$request_id = $this->recievedRequests()->where('friend_id' , $user->id)->first()->id;
if($request_id) {
return $this->recievedRequests()->updateExistingPivot($request_id , ['accepted' => true]) ;
}
return false ;
}
友谊表
Schema::create('friendships', function (Blueprint $table) {
$table->id();
$table->foreignId('user_id')->constrained()->onDelete('cascade')->onUpdate('cascade');
$table->foreignId('friend_id')->constrained()->onDelete('cascade')->onUpdate('cascade');
$table->timestamps();
$table->boolean('accepted')->default(false);
$table->timestamps();
});
推荐阅读
- google-apps-script - 谷歌脚本将数据从一张表传输到另一张表
- javascript - 有没有办法在不使用 iframe、object 或 embed 的情况下在 angular 6 对话框中加载外部 URL?
- php - Laravel 验证器。无法同时检索错误和输入
- mysql - 当所有都相等时如何仅获取子记录 100%的mysql查询
- ms-access - MS Access - 创建一个模块,使用 VBA 通过不同的组合框过滤子表单
- java - 在java中从命令行创建新的avd
- python - Tensorflow 对象检测 - 创建 TFRecord 时出错
- python - Django:我们可以使用 django ORM 将 dict 直接加载到数据库吗
- javascript - 使用元素ui和vue js在选择更改后将焦点设置在输入上
- excel - 如果有一个公式是参考单元格,有没有办法让 ISTEXT 公式忽略?