我想显示用户的好友。但是我得到以下错误:
Builder.php第2345行BadMethodCallException:调用undefined方法阐明 数据库查询建设者:朋友()
FriendController:
<?php
namespace AppHttpControllers;
use IlluminateHttpRequest;
use AppHttpRequests;
use AppUser;
use Auth;
class FriendController extends Controller
{
public function getIndex(){
$friends=Auth::user()->friends();
return view('friends',['friends'=>$friends]);
}
}
路线:
Route::get('/friends',[
'uses' => 'FriendController@getIndex',
'as' => 'friends',
'middleware' => 'auth:web'
]);
用户模式:public function getName(){
if($this->firstname && $this->lastname){
return "{$this->firstname} {$this->lastname}";
}
if($this->firstname)
return $this->firstname;
return null;
}
public function getNameOrUsername(){
return $this->getName() ?: $this->username;
}
public function getFirstNameOrUsername() {
return $this->firstname ?: $this->username;
}
我的观点:
<div id="grp" class="panel-heading">
<h3 id="grouptitle" class="panel-title">Your Friends</h3>
@if(!$friends->count())
<p>you have no friends</p>
@else
@foreach($friends as $user)
@include('userblock')
@endforeach
@endif
</div>
userblock.blade:
<div class="media">
<a href="{{ route('myplace', ['username'=>$user->username]) }}" class="pull-left">
<img src="" class="media-object" alt="{{ $user->getNameOrUsername() }}">
</a>
<div class="media-body">
<h4 class="media-heading"><a href="#">{{ $user->getNameOrUsername() }}</a></h4>
</div>
看起来你在作为用户的user
模型和它的朋友(又一个用户)之间有多对多的关系。因此,我们可以使用belongsToMany()
方法作为Users
来检索所选用户的好友。
为此,将以下函数添加到User
模型。
public function friends(){
return $this->belongsToMany('AppUser::class','friends','user_id','friend_id')->withPivot('accepted');
}
获取当前登录用户的好友,使用如下命令:
$friends = Auth::user()->friends()->get();
假设friends
是相关用户,并且您的user
表中有friend_id
列,您可以在User
模型中添加friends
方法:
public function friends()
{
return $this->hasMany(AppUser::class, 'friend_id');
}
你可以在这里阅读更多关于关系的内容。您还可以使用包来满足此需求。或者在SO上搜索"self - reference relation laravel"