laravel 你能创建一个新的 Model 实例而不将它保存到数据库吗

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

Can you create a new Model instance without saving it to the database

laravellaravel-5

提问by ajon

I want to create a whole bunch of instances of a model object in Laravel, then pick the optimal instance and save it to the database. I know that I can create an instance with Model::create([]), but that saves to the database. If possible I'd like to create a bunch of models, then only "create" the one that is best.

我想在 Laravel 中创建一大堆模型对象的实例,然后选择最佳实例并将其保存到数据库中。我知道我可以用 来创建一个实例Model::create([]),但这会保存到数据库中。如果可能的话,我想创建一堆模型,然后只“创建”最好的一个。

Is this possible?

这可能吗?

I am using Laravel 5.0

我正在使用 Laravel 5.0

回答by Joseph Silber

You create a new model simply by instantiating it:

您只需通过实例化即可创建新模型:

$model = new Model;

You can then save it to the database at a later stage:

然后,您可以在稍后阶段将其保存到数据库中:

$model->save();

回答by Kris Tremblay

You can create instances with Model::make(). It works the same way as createbut it doesn't save it.

您可以使用Model::make(). 它的工作方式与create但不保存它的方式相同。

Whether or not this is best practice is another matter entirely.

这是否是最佳实践完全是另一回事。

回答by Dan

Yes, it is possible different ways: you can use the mass assignmentwithout saving.

是的,可能有不同的方式:您可以使用质量分配而无需保存。

Please remember to set first the $fillableproperty in your model.

请记住首先$fillable在您的模型中设置属性。

WAY #1: using the method fill

方式#1:使用方法填充

$model = new YourModel;

$model->fill([
    'field' => 'value',
    'another_field' => 'another_value'
]);

$model->save();

WAY #2: using the constructor

方式#2:使用构造函数

$model = new YourModel([
    'field' => 'value',
    'another_field' => 'another_value'
]);

$model->save();

Laravel documentation: https://laravel.com/docs/5.7/eloquent

Laravel 文档:https://laravel.com/docs/5.7/eloquent