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
Can you create a new Model instance without saving it to the database
提问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 create
but 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 $fillable
property 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