Laravel 保存模型和关系
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16957004/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Laravel Saving A Model And Relationships
提问by sjess
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"
多年来的 DBTable 有一个字段“movie_year”和“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:
我正在尝试用新数据更新 Model Years,但似乎无法完成。我尝试了以下方法:
$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.
眼睛在 $movies->year 行上,其他一切正常。
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.
我不知道如何更新与电影模型有关的年模型。
回答by DerLola
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
官方方法是使用附加、同步或关联方法。这些方法在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().
要删除关系(不是电影或年份),请使用 detach()。