簡體   English   中英

調用未定義的方法(laravel 5.2)

[英]Call to undefined method (laravel 5.2)

我想顯示用戶的朋友。 但是我收到以下錯誤:

Builder.php第2345行中的BadMethodCallException:調用未定義的方法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>

假設friends是相關用戶,並且在user表中有一個friend_id列,則可以在User模型中添加friends方法:

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

您可以在這里閱讀更多有關關系的信息 您也可以根據需要使用包裝 或在SO上搜索有關“自我參照關系laravel”的信息

看來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();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM