调用未定义方法(版本5.2)


Call to undefined method (laravel 5.2)

我想显示用户的好友。但是我得到以下错误:

Builder.php第2345行BadMethodCallException:调用undefined方法阐明' '数据库查询'建设者:朋友()

FriendController:

 <?php
namespace App'Http'Controllers;
use Illuminate'Http'Request;
use App'Http'Requests;
use App'User;
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('App'User::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('App'User::class, 'friend_id');
}

你可以在这里阅读更多关于关系的内容。您还可以使用包来满足此需求。或者在SO上搜索"self - reference relation laravel"