如何编辑 Laravel 集合中的项目
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/37586652/
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 edit items in laravel collection
提问by TyForHelpDude
I am new in laravel, I run a query and get rows from database and I want to edit a column of this rows before get them in view. So here is my code piece :
我是 laravel 的新手,我运行查询并从数据库中获取行,我想在查看这些行之前编辑这些行的列。所以这是我的代码片段:
$callPlans = CustomerCallPlan::whereNotNull('id');
foreach ($callPlans->get() as $callPlan) {
dd($callPlan);
}
And the output screenshot:
和输出截图:
I need to replace all the 'x' characters with '-' of numbertemplate
column..
我需要用numbertemplate
列的“-”替换所有的“x”字符..
回答by jedrzej.kurylo
If you want to do this transformations always for your model, you can just add the following accessor method to the model class:
如果您想始终为您的模型执行此转换,您只需将以下访问器方法添加到模型类:
public function getNumbertemplateAttribute() {
return str_replace('x', '-', $this->attributes['numbertemplate']);
}
Now everytime you access $customerCallPlan->numbertemplateyou will get the converted string.
现在每次访问$customerCallPlan->numbertemplate 时,您都会得到转换后的字符串。
Otherwise just convert the column when you fetch the data:
否则,只需在获取数据时转换列:
$plans = $callPlans->get()->map(function($plan) {
$plan->numbertemplate = str_replace('x', '-', $plan->numbertemplate);
return $plan;
});
回答by Codearts
You could do the following:
您可以执行以下操作:
$callPlans = CustomerCallPlan::whereNotNull('id')->get();
foreach ($callPlans as $callPlan) {
$callPlan->numbertemplate = (whetever you need);
$callPlan->save(); //save the changes
}
Hope this was helpful.
希望这是有帮助的。
回答by Zakaria Acharki
You could use update()
and str_replace()
:
你可以使用update()
和str_replace()
:
$callPlans = CustomerCallPlan::whereNotNull('id');
foreach ($callPlans->get() as $callPlan) {
$callPlan->update(["numbertemplate"=>str_replace("x", "-", $callPlan->numbertemplate]);
}
Hope this helps.
希望这可以帮助。