laravel 反向一对一_Laravel保存数据一对一关系的最佳方法?

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.

解决方案

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;

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值