条款表:
Term_taxonomy表:
我的期限模型:
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;
}
}
My TermTaxonomy模型:
public function Term(){
return $this->belongsTo('Term');
}
然后在我的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代码非常难看,有没有最好的方法来保存数据一对一关系以及如何使用它?
谢谢,抱歉,我是laravel的新人。
答案 0 :(得分:0)
我觉得这很好..但你可以直接保存你的关系,而不用
$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;
}
}