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

Method Illuminate\Database\Eloquent\Collection::post does not exist

很抱歉提出这样一个愚蠢的问题,但我现在处于死胡同,我正在使用 Laravel(顺便说一句,第一次)进行个人项目,我 运行 遇到了一些问题。

我尝试做 {{ $kategori->post()->count() }}(顺便说一句,这是可行的)但是用户 table。我已经设置了外键和东西。

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

我已经尝试编辑模型(User.phpPost.php)和控制器,但我仍然无法弄清楚哪里出了问题。

Post.php

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

User.php

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

控制器

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 查看

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

没看懂源码的主要用途 但是你可以使用下面的代码来计算关系

$user_post_count = User::find($id)->post()->count();
$all_user_with_post = User::all()->with('post');
$all_user_with_post_count = User::all()->withCount('post');

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

$user = User::post;

这应该是::Post.

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

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

您可以在视图中以这种方式访问​​计数:

{{$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,因为它是一对多的关系。