sjess
sjess

Reputation: 107

Laravel Saving A Model And Relationships

I have the following Model:

class Movie extends Eloquent {

protected $primaryKey = "movie_id";

public function detail()
{
    return $this->hasOne('Detail');
}

public function firstpage()
{
    return $this->hasOne('Firstpage');
}

public function country()
{
    return $this->belongsToMany('Countries','movies_countries','movie_id','country_id');
}

public function year()
{
    return $this->hasOne('Years');
}

public function media() {
    return $this->hasMany('Media');
}
}

This is the Model of interest:

class Years extends Eloquent {

protected $table = 'movies_years';
protected $primaryKey = "relation_id";

public function movie()
{
    return $this->belongsTo('Movie');
}

The DBTable for years has a field "movie_year" and "movie_id"

So, I have following problem, or understanding issue:

I'm trying to update the Model Years with new Data, but can't seem the get it done. I tried the following:

$movies = Movie::find($tmp['movie_id']);

$movies->title = $tmp['title'];
$movies->title_product = $tmp['title_product'];
$movies->title_orginal = $tmp['title_original'];

$movies->year = array('movie_year' => $tmp['movieyears']);

$movies->push();

The eye is on the $movies->year row, everything else works fine.

I also tried something stupid like:

$movies->year() = array('movie_year' => $tmp['movieyears']);

I don't know how to update the Years Model, which has a relation with the Movie Model.

Upvotes: 3

Views: 26230

Answers (1)

DerLola
DerLola

Reputation: 3918

The offical way would be using attach, sync or associate methods. These methods are described at http://laravel.com/docs/eloquent-relationships#inserting-related-models

In your case, you'd have to do something like this:

$movies->year()->attach($tmp['movieyears']);

To remove the relation (not the Movie or Year), use detach().

Upvotes: 2

Related Questions