laravel - 方法 Illuminate\Database\Eloquent\Collection::post 不存在

标签 laravel eloquent laravel-5.8

很抱歉问了这样一个愚蠢的问题,但我现在陷入了困境,我正在使用 Laravel 开发一个个人项目(顺便说一句),我遇到了一些问题。

我尝试执行 {{ $kategori->post()->count() }} (顺便说一句,这是有效的),但使用的是 Users 表。我已经设置了外键和其他东西。

我也尝试修改User.php(参见代码),但仍然没有按我的预期工作。我需要一些帮助。我使用 Laravel“php artisan make:auth

我尝试编辑模型(User.phpPost.php)和 Controller ,但我仍然无法弄清楚出了什么问题。

Post.php

public function user()
{
    return $this->belongsTo('App\User', 'user_id');
}

User.php

public function post()
{
   return $this->hasMany('App\Post','user_id');
}

Controller

use App\User;

// other methods in the Controller

public function index()
{
   $posts = post::paginate(5);
   $user = User::post;
   return view('index', compact('posts', 'user'));   
}

Blade View

{{ $user->post()->count() }}

最佳答案

您正在调用此行中不存在的 post 模型:

$user = User::post;

这应该是::帖子

如果您只想计算帖子数量,您应该使用 withCount()方法,这将计算帖子的数量而不加载它们,这会给你一些性能。

$user = User::find($id)->withCount('post'); // this will count the number of posts to the given user.
return view('index', compact('user'));   

您可以在 View 中通过以下方式访问计数:

{{$user->post_count}}

您还可以统计所有用户的帖子数量:

$users = User::all()->withCount('post');

并执行一个 foreach 循环来访问它们中的每一个:

@foreach($users as $user)
{{$user->post_count}}
@endforeach

文档:

If you want to count the number of results from a relationship without actually loading them you may use the withCount method, which will place a {relation}_count column on your resulting models.

注意:您应该将您的关系命名为 posts,而不是 post,因为它是一对多关系。

关于laravel - 方法 Illuminate\Database\Eloquent\Collection::post 不存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55679607/

相关文章:

php - 按聚合函数排序 Laravel Eloquent

php - 如何使用 Eloquent 方式通过具有嵌套关系(belongsToMany)的子类别来计算父类别中的产品

php - 如何在 Wappalyzer 上隐藏网站信息

laravel - 完整性约束违规 : 1052 Column 'updated_at' in field list is ambiguous

laravel - 按 slug 而不是按 id 搜索对象

php - -bash : laravel: command not found

php - 如何在 Laravel DB::insert 中返回我的 OUTPUT 子句

拉拉维尔 4 : Order by in a pivot table

mysql - 在 eloquent 中添加 if 语句然后加入另一个表

laravel - isset 或空 Laravel 中的偏移类型非法