Database 好友数在社交网络的标题中
我还在拉威尔学习,作为一个项目,我选择了我在CodeIgniter中已经拥有的社交网络 有人谁有更多的经验,在拉威尔作为我推荐我使用在我的头。刀片这个。Auth()->User()->GetFriendsCount() 我的用户模型Database 好友数在社交网络的标题中,database,laravel,relationships,Database,Laravel,Relationships,我还在拉威尔学习,作为一个项目,我选择了我在CodeIgniter中已经拥有的社交网络 有人谁有更多的经验,在拉威尔作为我推荐我使用在我的头。刀片这个。Auth()->User()->GetFriendsCount() 我的用户模型 public function friends() { return $this->hasMany('App\Models\Friends', 'receiver_id'); } public function 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
}
我在调用未定义的方法illumb\Database\Query\Builder::GetFriendsCount()时出错,得到以下结果
谁能帮助我,我将如何达到我的结果
如果未连接Auth()->User(),则返回null
尝试以下代码:
用户模型:
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()
您是否尝试过返回计数($this->friends)
?这个return$This->friends()->count()代码>应该可以工作。此错误调用未定义的方法illumb\Database\Query\Builder::GetFriendsCount()
表明您正在调用方法GetFriendsCount()在查询生成器对象上,因此我认为调用该方法的方式可能有问题,因为它似乎没有在用户对象上调用它尝试`$friends=Auth()->User()->friends;如果($friends)$total_friends=$friends->count()`你必须->得到朋友们。。。尝试返回计数($this->friends()->get())
Auth()不是一个方法,它是一个类,请尝试Auth::user()->getFriendsCount()
也将函数名更改为getFriendsCount(),作为psr标准,以小写开头。我得到了这个结果。>>>$u->getFriendsCount();=>←[35m4←[39m这没有帮助。问题是如果我将完整的查询写入标题,那么我会得到我想要的结果。如果我将相同的查询写入模型,那么我会得到相同的错误“调用undefined method Illumb\Database\query\Builder::getFriendsCount()'尝试使用关系调用->friends
和tinker中的方法,我相信你会解决的。抱歉,现在无法帮助你进一步调试。
Auth::user()->getFriendsCount()