在Laravel中更新关系模型

时间:2015-06-01 09:19:54

标签: php laravel laravel-5 relationship updating

我是Laravel 5的新手。我查看了教程" Laravel 5 Fundamentals"我有一个问题。

文章模型

public function category()
{
    return $this->belongsTo('App\Category');
}

类别模型

public function article()
{
    return $this->hasMany('App\Article');
}

ArticleController

public function create()
{
    $categories = Category::lists('name', 'id');

    return view('admin.article.create', compact('categories'));
}

public function store(ArticleRequest $request)
{
    $article = new Article($request->all());
    $category = Category::find($request->input('categories'));
    $article->category()->associate($category);
    \Auth::user()->article()->save($article);

    return \Redirect::to('/admin/article');
}

public function edit(Article $article)
{
    $categories = Category::lists('name', 'id');

    return view('admin.article.edit', compact('article', 'categories'));
}

public function update(Article $article, ArticleRequest $request)
{
    $article->update($request->all());

    return redirect('admin/article');
}

如何更新文章模型和相关的类别模型?

1 个答案:

答案 0 :(得分:0)

您可以像这样更新:(原始来源:http://laravel.com/docs/5.0/eloquent#insert-update-delete

public function update(Article $article, ArticleRequest $request)
{
    $newValues = $request->except('_method', '_token');
    foreach($newValues as $key => $value)
    {
         $article[$key] = $value;
    }
    $article->save();

    return redirect('admin/article');
}

public function update(Article $article, ArticleRequest $request)
{
    $article->title = $request->input('title');
    //all article's table columns = $request->input('corresponding_input_name')
    $article->save();

    return redirect('admin/article');
}

正如@patricus所说:

public function update(Article $article, ArticleRequest $request)
{
    $article->fill($request->all());
    $article->save();
    return redirect('admin/article');
}