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

时间:2019-04-14 20:12:16

标签: laravel eloquent laravel-5.8

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

我尝试使用{user}表执行{{ $kategori->post()->count() }}(顺便说一句)。我已经设置了外键和东西。

我也尝试过修改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'));   
}

刀片视图

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

2 个答案:

答案 0 :(得分:1)

我不明白源代码的主要目的 但是您可以使用以下代码来计算关系

$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');

答案 1 :(得分:0)

您正在调用此行中不存在的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'));   

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

{{$user->post_count}}

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

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

并执行一个foreach循环以访问其中的每一个:

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

文档:

  

如果您想在没有实际加载的情况下计算关系的结果数,则可以使用withCount方法,该方法将在结果模型上放置一个{relation} _count列。

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

相关问题