under5hell
under5hell

Reputation: 997

Laravel model eager loading is not working

I have a users table and posts table. A user can have many post, and a post only have a user. a typical 1:n relationship. what i wanna do is inserting post data trough user model (eager loading). like this one :

User::find(1)->posts()->insert(array(
            'title' => 'post 1',
            'body'  => 'lorem ipsum is just a dummy text'
        ));

this is User model :

class User extends \Eloquent {
    protected $fillable = ['username', 'email'];
    protected $table = 'users';

    public function posts()
    {
        return $this->hasMany('Post');
    }
}

this is my post model

class Post extends \Eloquent {
    protected $fillable = ['title', 'user_id', 'body'];
    protected $table = 'posts';

}

and this is the post migration ( i made the user_id foreign to this table in order to supprt the relationship)

Schema::create('posts', function(Blueprint $table)
        {
            $table->increments('id');
            $table->integer('user_id')->references('id')->on('user');
            $table->string('title');
            $table->text('body');
            $table->timestamps();
        });

The problem : the data is inserted but the user_id = 0 and timestamps = 00000000

would anyone tell me whats wrong with my code? thanks

Upvotes: 0

Views: 113

Answers (1)

JofryHS
JofryHS

Reputation: 5874

What you want is ->save(), not ->insert(). Read this link: http://laravel.com/docs/eloquent#inserting-related-models

->insert() is using QueryBuilder which has no knowledge of your relationship, while ->save() does (or ->saveMany())

User::find(1)->posts()->save(new Post(
            'title' => 'post 1',
            'body'  => 'lorem ipsum is just a dummy text'
        ));

Upvotes: 1

Related Questions