本文介绍了Laravel一对一保存数据的最佳方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
条款表:
- term_id
- 名称
- sl
Term_taxonomy表:
Term_taxonomy table:
- term_taxonomy_id
- term_id
- 说明
我的任期模式:
public function TermTaxonomy(){
return $this->hasOne('TermTaxonomy');
}
public function saveCategory($data){
$validator = Validator::make($data,$this->rules);
if($validator->passes()){
$this->name = $data['name'];
$this->slug = $data['slug'];
if($this->save()){
$category_taxo = new TermTaxonomy;
$category_taxo->term_id = $this->lastCategoryId();
$category_taxo->taxonomy = 'category';
$category_taxo->description = $data['description'];
if($category_taxo->save()){
return true;
}else{
return false;
}
}else{
return false;
}
}else{
$this->errors = $validator;
return false;
}
}
我的术语分类模型:
public function Term(){
return $this->belongsTo('Term');
}
然后在我的CategoriesController中
then in my CategoriesController
public function store()
{
$data = Input::all();
$category = new Term;
if($category->saveCategory($data)){
return Redirect::route('admin_posts_categories')->withSuccess('Category successfully added.');
}
else{
return Redirect::route('admin_posts_categories')->withError('Failed to add category.')->withErrors($category->validation_messages())->withInput();
}
}
它可以工作,但是我认为我的laravel代码很难看,有没有最好的方法来一对一保存数据以及如何使用它?
It works, but i think my laravel code very ugly, is there any best way method to save data one to one relationships and how to use it ?
谢谢,抱歉,我是laravel的新朋友.
Thanks, sorry i am new in laravel.
推荐答案
我认为这很好..但是您可以直接保存您的恋情,而无需
I think it is good.. but you can save your relationship directly without
$category_taxo->term_id = $this->lastCategoryId();
尝试一下:
public function saveCategory($data){
$validator = Validator::make($data,$this->rules);
if($validator->passes()){
$this->name = $data['name'];
$this->slug = $data['slug'];
if($this->save()){
# new TermTaxonomy
$TermTaxonomy = new TermTaxonomy;
$TermTaxonomy->taxonomy = 'category';
$TermTaxonomy->description = $data['description'];
# Save related TermTaxonomy
if($this->TermTaxonomy()->save($TermTaxonomy)){
return true;
}else{
return false;
}
}else{
return false;
}
}else{
$this->errors = $validator;
return false;
}
}
这篇关于Laravel一对一保存数据的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!