json 如何在 Eloquent 模型中使用 Request->all()
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35630138/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to use Request->all() with Eloquent models
提问by patricus
I have a lumen application where I need to store incoming JSON Request. If I write a code like this:
我有一个流明应用程序,我需要在其中存储传入的 JSON 请求。如果我写这样的代码:
public function store(Request $request)
{
if ($request->isJson())
{
$data = $request->all();
$transaction = new Transaction();
if (array_key_exists('amount', $data))
$transaction->amount = $data['amount'];
if (array_key_exists('typology', $data))
$transaction->typology = $data['typology'];
$result = $transaction->isValid();
if($result === TRUE )
{
$transaction->save();
return $this->response->created();
}
return $this->response->errorBadRequest($result);
}
return $this->response->errorBadRequest();
}
It works perfectly. But use Request in that mode is boring because I have to check every input field to insert them to my model. Is there a fast way to send request to model?
它完美地工作。但是在那种模式下使用 Request 很无聊,因为我必须检查每个输入字段才能将它们插入到我的模型中。有没有一种快速的方法可以向模型发送请求?
回答by patricus
You can do mass assignment to Eloquent models, but you need to first set the fields on your model that you want to allow to be mass assignable. In your model, set your $fillablearray:
您可以对 Eloquent 模型进行批量分配,但您需要首先在模型上设置您希望允许批量分配的字段。在您的模型中,设置您的$fillable数组:
class Transaction extends Model {
protected $fillable = ['amount', 'typology'];
}
This will allow the amountand typologyto be mass assignable. What this means is that you can assign them through the methods that accept arrays (such as the constructor, or the fill()method).
这将允许amount和typology可批量分配。这意味着您可以通过接受数组的方法(例如构造函数或fill()方法)来分配它们。
An example using the constructor:
使用构造函数的示例:
$data = $request->all();
$transaction = new Transaction($data);
$result = $transaction->isValid();
An example using fill():
使用示例fill():
$data = $request->all();
$transaction = new Transaction();
$transaction->fill($data);
$result = $transaction->isValid();
回答by chanafdo
You can either use fillmethod or the constructor. First you must include all mass assignable properties in fillableproperty of your model
您可以使用fillmethod 或constructor. 首先,您必须在fillable模型的属性中包含所有可分配的质量属性
Method 1 (Use constructor)
方法一(使用构造函数)
$transaction = new Transaction($request->all());
Method 2 (Use fillmethod)
方法二(使用fill方法)
$transaction = new Transaction();
$transaction->fill($request->all());

