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

时间:2015-01-23 10:20:38

标签: php laravel laravel-4

条款表:

  • term_id
  • 名称
  • 蛞蝓

Term_taxonomy表:

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

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

1 个答案:

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