【问题标题】:Method Illuminate\Database\Eloquent\Collection::post does not exist方法 Illuminate\Database\Eloquent\Collection::post 不存在
【发布时间】:2019-09-04 20:53:24
【问题描述】:

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

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

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

我已尝试编辑模型(User.php 和 Post.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() }}

【问题讨论】:

    标签: laravel eloquent laravel-5.8


    【解决方案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');
    

    【讨论】:

      【解决方案2】:

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

      文档:

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

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

      【讨论】:

        猜你喜欢
        • 2020-11-21
        • 2021-09-08
        • 2020-11-13
        • 2019-12-11
        • 2020-02-04
        • 2019-11-12
        • 2019-05-24
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多