朋友们算在社交网络的标题中

时间:2016-01-22 08:59:11

标签: database laravel relationships

我还在Laravel学习,作为项目,我选择了我已经在CodeIgniter中使用的社交网络。

我在Laravel有更多经验的人建议我在我的header.blade中使用。 AUTH() - >用户() - > GetFriendsCount()

我的用户模型

public function friends()
{
    return $this->hasMany('App\Models\Friends', 'receiver_id');
}

public function GetFriendsCount()
{
    return $this->friends->count(); //didn't help
    return $this->friends()->count(); //didn't help
}

我得到以下错误调用未定义的方法Illuminate \ Database \ Query \ Builder :: GetFriendsCount()

谁可以帮助我,我将如何达到我的结果?

2 个答案:

答案 0 :(得分:0)

  

如果你没有连接Auth() - > User()返回null

in.myTable.length

答案 1 :(得分:0)

尝试使用此代码:

用户模型:

public function friends()
{
    return $this->hasMany('App\Models\Friends', 'receiver_id');
}

public function getFriendsCount()
{
    return $this->friends()->count();
}

尝试在artisan tinker中使用模型实例,然后在视图中运行它。你可以这样做:

php artisan tinker // get into tinker

$u = App\Models\User::first(); // grab the first user in the db, they should have some App\Models\Friends linked to them

$u->getFriendsCount(); // test out the method

您可以在刀片视图中运行该方法,如下所示:

Auth::user()->getFriendsCount()
相关问题