解决方案:我使用数据库外观DB::select()
来运行原始SQL查询。
我有两个表用户(id,用户名,城市,国家)和朋友(id,user_id,friend_id,状态)。 “用户”表存储用户信息,“朋友”表存储当前登录的用户ID,friend_id是向当前用户发送朋友请求的用户的ID,状态将被“接收”。我想显示要发送请求给当前用户的用户信息。我的数据库查询语法正确吗?如果不使用嵌套的子查询,则可以看到正确的输出。预先感谢!
我的数据库查询:
$friendrequests = DB::table('users')->select(['username','city','country'])->where('id',DB::table('friends')->select('friend_id')->where([['status','received'],['user_id',$user->id]]));
我的html:
@extends('layouts.master')
@section('title')
Friend Requests
@endsection
@section('content')
@include('includes.message-block')
<section class="row requests">
<div class="col-md-6 col-md-offset-3">
<header><h3>Friend Requests</h3></header>
<div class="requestlist">
<header><h2>You have request from:</h2></header>
@foreach($users as $user)
<p>Name: {{ $user->username }}<br />City: {{ $user->city }}<br />Country:{{ $user->country }}</p>
<div class="interaction">
//stuff here
</div>
@endforeach
<a href="{{ URL::previous() }}">Back</a>
</div>
</div>
</section>
@endsection
路线:
Route::get('/friendrequests',[
'uses' => 'FriendController@getFriendRequests',
'as' => 'friendrequests',
'middleware' => 'auth'
]);
控制器(如果我不使用嵌套的子查询,则可以使用):
public function getFriendRequests()
{
$user = Auth::user();
$friendrequests = DB::table('users')
->select(['username','city','country'])
->where('id',
DB::table('friends')->select('friend_id')->where([['status','received'],['user_id',$user->id]])->get())->get();
return view('friendrequests',['users' => $friendrequests]);
}
答案 0 :(得分:1)
请尝试这样做可能有帮助
$friendrequests = DB::table('users')
->select(['username','city','country'])
->whereIn('id', function($query) use($user) {
$query->select('friend_id')
->from('friends')
->where('status', 'received')
->where('user_id', $user->id);
})->get();
答案 1 :(得分:0)
您可以使用“ hasManyThrough”方法解决此问题。在用户模型中,您应该执行以下操作:
class User extends Model{
//... your code here
public function possibleFriends(){
$this->hasManyThrough(User::class, Friend::class, 'friend_id', 'id')->wherePivot('status', 'received');
}
}
official docs中的更多详细信息。