1

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

模型用户.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');
    }
    //----

模型博客.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();
});

当我从 调用Blog::with('author')->get();BlogsController,我收到此错误:-

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

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

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

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

4

1 回答 1

3

你会喜欢和讨厌这个答案,请更改belongs_tobelongsTohas_manytohasManyhas_oneto也是如此hasOne

Laravel 4 转而使用骆驼案例作为方法。在 eloquent 模型上找不到您的方法,它回退到在查询构建器上调用它,laravel 这样做是为了允许快捷地使用 和 之类的select()方法where()

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

于 2013-10-29T07:37:34.037 回答