سؤال

I have two models User.php and Blog.php and the content,

Model 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');
    }
    //----

Model Blog.php

<?php

class Blog extends Eloquent {

   protected $guarded = array();

   public static $rules = array();

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

The Controller, 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
       );
    }
    //-----

The blogs schema,

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

And the users schema,

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();
});

When I call Blog::with('author')->get(); from BlogsController, I am getting this error:-

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

And when I change Blog::with('author')->get(); to Blog::with('author')->all();, the error become:-

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

I am using latest update for Laravel 4. What is the wrong with my code?

هل كانت مفيدة؟

المحلول

Your going to love and hate this answer, change belongs_to to belongsTo. Same goes for has_many to hasMany and has_one to hasOne.

Laravel 4 moved to using camel case for methods. Your method not being found on the eloquent model, it falls back to calling it on the query builder, laravel does this to allow short cutting to methods like select() and where().

The second error you were getting, when using all(), is because all() is a static method defined on eloquent and does not work with eager loading. get() is effectively the same thing as all().

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top