Laravel best way to save data one to one relationships?

陌路散爱 提交于 2019-12-11 04:19:20

问题


Terms table:

  • term_id
  • name
  • slug

Term_taxonomy table:

  • term_taxonomy_id
  • term_id
  • description

My Term model:

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 model:

public function Term(){
    return $this->belongsTo('Term');
}

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

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 ?

Thanks, sorry i am new in laravel.


回答1:


I think it is good.. but you can save your relationship directly without

$category_taxo->term_id = $this->lastCategoryId();

Try this:

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


来源:https://stackoverflow.com/questions/28107658/laravel-best-way-to-save-data-one-to-one-relationships

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!