Laravel 保存数据一对一关系的最佳方式?

Laravel best way to save data one to one relationships?

条款table:

Term_taxonomy table:

我的学期模型:

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;
    } 
}

我的 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 的新人。

我觉得挺好的..不过不用

可以直接挽回你们的关系
$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;
    } 
}