Laravel Eloquent:插入数据

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31168377/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 11:51:59  来源:igfitidea点击:

Laravel Eloquent: inserting data

laraveleloquent

提问by be-codified

I am sending a bunch of data through post method. For now I am using a fully working solution:

我正在通过post 方法发送一堆数据。现在我正在使用一个完全有效的解决方案:

$dataClient = new Client;
$dataClient->name    = $post['client']['name'];
$dataClient->address = $post['client']['address'];
...
$dataClient->save();        

I am wondering if there is a shorter solution? Like posting an array and Laravel could map keys to db fields?

我想知道是否有更短的解决方案?就像发布数组一样,Laravel 可以将键映射到 db 字段吗?

What if you would add something more, like calculated value upon?

如果您要添加更多内容,例如计算值,该怎么办?

Example:

例子:

$dataClient = new Client;
Then map array keys to db keys
$dataClient->someField = someCalculatedValue 
$dataClient->save();

Thank you in advance.

先感谢您。

回答by lukasgeiter

You have quite a few options when it comes to creating models from a data array. If you want to directly insert it into the database, the easiest way is create()

从数据数组创建模型时,您有很多选择。如果想直接插入到数据库中,最简单的方法是create()

Client::create($post['client']);

If you want to change some things afterwards or just not save it right away, just pass your data to the constructor.

如果您想在之后更改某些内容或只是不立即保存,只需将您的数据传递给构造函数。

$client = new Client($post['client']);
$client->someField = 'some value';
$client->save();

And finally, the last option, calling fill()manually. This method is used internally for create()as well as in the constructor.

最后,最后一个选项,fill()手动调用。此方法在内部用于create()以及在构造函数中使用。

$client = new Client();
$client->fill($post['client']);
$client->save();


Note:for all methods aboveyou'll need to set up the fillableattributes in your model. This is to protect against malicious user input (request data).

注意:对于上述所有方法,您需要在模型中设置可填充属性。这是为了防止恶意用户输入(请求数据)。

protected $fillable = ['name', 'address', 'etc'];

More information about Mass Assignment

有关批量分配的更多信息

回答by Phi Nguyen

Eloquent has create and updatemethods which will insert massive data. For example :

Eloquent 有create 和 update方法,可以插入海量数据。例如 :

inputs = ['name' => 'value','address' => 'value'];
Client::create(inputs)

It will automatically map fields in Eloquent.

它将自动映射 Eloquent 中的字段。

回答by Poncho

Have you tried something like this?

你有没有尝试过这样的事情?

$dataClient = new Client;
$dataClient->fill($client);
$dataClient->save();

Depending on how you set up your Client model and what fields you set as guarded/fillable, the fill method will automatically map the data with their respective fields.

根据您设置 Client 模型的方式以及您将哪些字段设置为受保护/可填充,fill 方法将自动将数据与其各自的字段进行映射。