【问题标题】:BadMethodCallException with eager loading in Laravel 4在 Laravel 4 中急切加载的 BadMethodCallException
【发布时间】:2013-10-29 07:33:39
【问题描述】:

我有两个模型User.php 和Blog.php 和内容,

模型User.php

<?php

use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableInterface;

class User extends Eloquent implements UserInterface, RemindableInterface {

    protected $softDelete = true;

    protected $table = 'users';

    protected $hidden = array('password');

    //-----
    public function blogs()
    {
       return $this->has_many('Blog');
    }
    //----

模型Blog.php

<?php

class Blog extends Eloquent {

   protected $guarded = array();

   public static $rules = array();

   public function author()
   {
     return $this->belongs_to('User', 'author_id');
   }
}

控制器,BlogsController.php

<?php

class BlogsController extends BaseController {

    public function index()
    {
           $posts = Blog::with('author')->get();

           return Response::json(array(
              'status'   => 'success',
              'message'  => 'Posts successfully loaded!',
              'posts'    => $posts->toArray()),
              200
       );
    }
    //-----

博客架构,

Schema::create('blogs', function(Blueprint $table) {
     $table->increments('id');
     $table->string('title');
     $table->text('body');
     $table->integer('author_id');
     $table->timestamps();
     $table->softDeletes();
});

用户架构,

Schema::create('users', function(Blueprint $table) {
   $table->integer('id', true);
   $table->string('name');
   $table->string('username')->unique();
   $table->string('email')->unique();
   $table->string('password');
   $table->timestamps();
   $table->softDeletes();
});

当我从BlogsController 呼叫Blog::with('author')-&gt;get(); 时,我收到了这个错误:-

"type":"BadMethodCallException","message":"Call to undefined method Illuminate\\Database\\Query\\Builder::belongs_to()"

当我将Blog::with('author')-&gt;get(); 更改为Blog::with('author')-&gt;all(); 时,错误变为:-

"type":"BadMethodCallException","message":"Call to undefined method Illuminate\\Database\\Query\\Builder::all()"

我正在使用 Laravel 4 的最新更新。我的代码有什么问题?

【问题讨论】:

    标签: php laravel laravel-4 eloquent eager-loading


    【解决方案1】:

    您会喜欢和讨厌这个答案,请将belongs_to 更改为belongsTo。 has_many 到 hasMany 和 has_one 到 hasOne 也是如此。

    Laravel 4 开始使用驼峰式大小写方法。在 eloquent 模型上找不到您的方法,它回退到在查询构建器上调用它,laravel 这样做是为了允许快捷地使用像 select() 和 where() 这样的方法。

    您在使用 all() 时遇到的第二个错误是因为 all() 是在 eloquent 上定义的静态方法,并且不适用于预加载。 get() 实际上与 all() 相同。

    【讨论】:

    猜你喜欢
    • 2014-08-13
    • 2015-03-19
    • 1970-01-01
    • 1970-01-01
    • 2013-03-27
    • 1970-01-01
    • 1970-01-01
    • 2014-12-28
    • 2013-07-18
    相关资源
    最近更新 更多