Laravel 中如何在 save 的同时保存 nested resource
最近想通过一个小blog的项目学习laravel,articles和tags是多对多的关系,现在在save的时候遇到了问题,laravel的eloquent怎样才能像active record一样在save article的同时save其所属的tags。我的代码如下:
另外,请问laravel有啥相关的书籍或者教程吗?感觉laravel相关的资料比rails还少…
// Article.php
<?php namespace App;
use Illuminate\Database\Eloquent\Model;
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->tags()->attach($tags)-save()) {
retur n redirect('console/articles')->with('success', '发布成功');
} else {
return redirect()->back()->withInput();
}
}
//...
另外,请问laravel有啥相关的书籍或者教程吗?感觉laravel相关的资料比rails还少…
0 个回复