Laravel 如何更新一对一的关系?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28144442/
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 How to update one to one relationships?
提问by Dark Cyber
Terms table:
术语表:
- term_id
- name
- slug
- term_id
- 姓名
- 蛞蝓
Term_taxonomy table:
Term_taxonomy 表:
- term_taxonomy_id
- term_id
- description
- term_taxonomy_id
- term_id
- 描述
My Term model:
我的术语模型:
public function TermTaxonomy(){
return $this->hasOne('TermTaxonomy');
}
My TermTaxonomy model:
我的术语分类模型:
public function Term(){
return $this->belongsTo('Term');
}
My Categories controller:
我的类别控制器:
public function update($id){
echo "$id"; // echo success
echo $data['name']; // it should update name field in term table
echo $data['slug']; // it should update slug field in term table
echo $data['TermTaxonomy']['description']; // it should update description field in termtaxonomy table
}
how i can update one to one relationships ? maybe with push()
我如何更新一对一的关系?也许用 push()
Thanks, sorry i am new in laravel.
谢谢,对不起,我是laravel的新手。
回答by crabbly
You can use Eloquent's update()
method: https://laravel.com/docs/5.4/eloquent#updates
您可以使用 Eloquent 的update()
方法:https: //laravel.com/docs/5.4/eloquent#updates
$Term = Term::with('TermTaxonomy')->find($id);
$Term->name = $data['name'];
$Term->slug = $data['slug'];
// Save The Term first
$Term->save();
// Now update the relation
$Term->TermTaxonomy->update([
'taxonomy' => 'category',
'description' => $data['TermTaxonomy']['description']
]);
回答by Dark Cyber
as Jarek Tkaczyk comment in this question Laravel eloquent: Update A Model And its Relationships
正如 Jarek Tkaczyk 在这个问题中的评论Laravel eloquent: Update A Model And its Relationships
There is no other way, as Eloquent currently doesn't know what relations are on the model until you call them as dynamic property, load with load method, eager load etc. (push works only with loaded relations that are present in model's relations array)
没有其他方法,因为 Eloquent 目前不知道模型上有什么关系,直到您将它们称为动态属性、使用 load 方法加载、预先加载等(推送仅适用于模型的关系数组中存在的加载关系)
so i use this code.
所以我使用这个代码。
$Term = Term::with('TermTaxonomy')->find($id);
$Term->name = $data['name'];
$Term->slug = $data['slug'];
$Term->TermTaxonomy->taxonomy = 'category';
$Term->TermTaxonomy->description = $data['TermTaxonomy']['description'];
$Term->push();
and it works. Term and TermTaxonomy table is updated, but if change push() to save() it only update Term table even TermTaxonomy relationships already loaded with Eager load Term::with('TermTaxonomy')
它有效。Term 和 TermTaxonomy 表已更新,但如果将 push() 更改为 save() 它只会更新 Term 表,即使 TermTaxonomy 关系已经加载了 Eager 负载Term::with('TermTaxonomy')
Thanks for all :D
谢谢大家:D