在laravel中保存时保存相关资源

时间:2015-04-17 07:10:36

标签: php laravel eloquent

文章和相关标签相关many to many 如何在创建新文章时将标签同步到交易中的文章?

Article.php

class Article extends Model {

  protected $fillable = ['title', 'body'];

  public function tags()
  {
    return $this->belongsToMany('App\Tag', 'article_tags');
  }

}

ArticlesController.php

public function store(StoreArticleRequest $request)
{
  if ($request->has('article.tags_attributes.value')) {
    $tags_value = $request->input('article.tags_attributes.value');
    $splited_tags_value = explode(',', $tags_value);

    if (count($splited_tags_value) > 0) {
      $tags = [];
      foreach(@$splited_tags_value as $tag_value) {
        $tags[] = Tag::firstOrCreate(['value' => trim($tag_value)]);
      }
    }
  }

  $article = new Article($request->input('article'));
  if ($article->save()->tags()->sync($tags)) {
    return redirect('console/articles')->with('success', '...');
  } else {
    return redirect()->back()->withInput();
  }
}

1 个答案:

答案 0 :(得分:0)

您可以像这样进行数据库事务。

public function store(StoreArticleRequest $request)
{
  if ($request->has('article.tags_attributes.value')) {
    $tags_value = $request->input('article.tags_attributes.value');
    $splited_tags_value = explode(',', $tags_value);

    if (count($splited_tags_value) > 0) {
      $tags = [];
      foreach(@$splited_tags_value as $tag_value) {
        $tags[] = Tag::firstOrCreate(['value' => trim($tag_value)]);
      }
    }
  }

  DB::transaction(function() {
    $article = new Article($request->input('article'));
    $article->save();
    $syncResult=$article->tags()->sync($tags);
  });

  if ($syncResult) {
    return redirect('console/articles')->with('success', '...');
  } else {
    return redirect()->back()->withInput();
  }
}