调用未定义的方法 Illuminate\Database\Query\Builder::post()

Call to undefined method Illuminate\Database\Query\Builder::post()

我在使用查询构建器时遇到问题,在路由文件中使用 post() 时出现未定义方法错误。

一般我用

的return
User::find($id)->post; 

但是当我将 post 作为函数调用时,它不起作用并给我:

Call to undefined method Illuminate\Database\Query\Builder::post()

用户模型

<?php

namespace App;

use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{


  protected $fillable = [
    'name', 'email', 'password',
 ];

 protected $hidden = [
     'password', 'remember_token',
 ];


 protected function post()
 {       
     return $this->hasOne('App\Post');  
 }

 }

路线

  Route::get('/', function () {
  return view('welcome');
  });



  Route::get('/user/{id}/post',function($id){

  return User::find($id)->post()->get();    

  });

试试这个:

路线

Route::get('/user/{id}/post',function($id){

   return User::with('post')->find($id);    

});

您的用户 class 中的 post() 方法需要是 public。现在它受到保护,这意味着外部 classes 无法访问它。

The post() method in your User class needs to be public. Right now it's protected, which means outside classes can't access it. ~ @jackel414

正如 Jackel414 提到的,您的 post() 功能受到保护,您需要 public 才能访问它。

我注意到你是 运行 一对一关系上的 get() 函数,这个函数旨在带回数据集合,除非你传递一个 id 作为参数,最好使用以下示例:

return User::find($id)->post;

return User::with('post')->find($id);

或者,您可以带回构建器以进一步扩展您的查询。

return User::find($id)->post();