我有一个 lumen 应用程序,需要在其中存储传入的 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();
}
它工作完美。但是在这种模式下使用 Request 很无聊,因为我必须检查每个输入字段以将它们插入到我的模型中。有没有一种快速的方法向模型发送请求?
您可以对 Eloquent 模型进行批量分配,但您需要首先在模型上设置允许批量分配的字段。在您的模型中,设置您的$fillable
array:
class Transaction extends Model {
protected $fillable = ['amount', 'typology'];
}
这将允许amount
and typology
可批量分配。这意味着您可以通过接受数组的方法(例如构造函数或fill()
方法)。
使用构造函数的示例:
$data = $request->all();
$transaction = new Transaction($data);
$result = $transaction->isValid();
一个使用的例子fill()
:
$data = $request->all();
$transaction = new Transaction();
$transaction->fill($data);
$result = $transaction->isValid();
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)