官方中文文档在这里:
http://laravel-china.org/docs/5.1/eloquent#%E6%89%B9%E9%87%8F%E8%B5%8B%E5%80%BC
我先来说明一下一个场景:
你想要往数据库中存评论,在控制器的代码如下:
设想一下如果这个评论表的字段有很多,岂不是要一个字段一个字段的存储,代码量太高。laravel框架提供了一个叫做批量赋值的功能:$comment->comment_id= $id; $comment->title = $name; $comment->url = $url; $comment->introduction = $profile; if ($comment->save()) { return redirect('admin/comment'); } else {return redirect()->back()->withInput()->withErrors('保存失败!')
控制器代码如下:
public function store(Request $request) { if (Comment::create($request->all())) { return redirect()->back(); } else { return redirect()->back()->withInput()->withErrors('评论发表失败!'); } }
对应的App\models中的Comment类:
<?php namespace App; use Illuminate\Database\Eloquent\Model; class Comment extends Model {protected $fillable = ['nickname', 'email', 'website', 'content','article_id'];}
protected $fillable= ['nickname','email','website','content','article_id'];
这一行就表示控制器中得到的数据全部存入相应字段,是不是很简单方便?
本文介绍了Laravel 5.1框架中的批量赋值功能,通过官方中文文档链接提供了详细解释。在示例场景中,展示了如何在控制器中批量保存评论数据到数据库,使用Comment模型的创建方法实现数据的便捷存储。
1048

被折叠的 条评论
为什么被折叠?



