我有两个模型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();
});
当我从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的最新更新。我的代码有什么问题?
答案 0 :(得分:3)
你会爱上并讨厌这个答案,将belongs_to
更改为belongsTo
。 has_many
到hasMany
和has_one
到hasOne
也是如此。
Laravel 4转向使用驼峰盒进行方法。你的方法没有在雄辩的模型中找到,它回退到在查询构建器上调用它,laravel这样做是为了允许短切到select()
和where()
等方法。
使用all()
时,您获得的第二个错误是因为all()
是在eloquent上定义的静态方法,并且不适用于预先加载。 get()
实际上与all()
完全相同。