调用未定义的方法(laravel 5.2)

时间:2016-08-10 08:53:49

标签: php laravel laravel-5 laravel-5.2

我想要显示用户的朋友。但我收到以下错误:

  

Builder.php第2345行中的BadMethodCallException:调用undefined   方法Illuminate \ Database \ Query \ Builder :: friends()

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>

2 个答案:

答案 0 :(得分:1)

假设friends是相关用户,并且您的friend_id表格中有user列,则可以在friends模型中添加User方法:

public function friends()
{
    return $this->hasMany(\App\User::class, 'friend_id');
}

您可以阅读有关关系here的更多信息。您也可以使用package来满足此需求。或者在SO上搜索“自我参照关系laravel”

答案 1 :(得分:1)

似乎您在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();