主义/ Symfony如何使用数组中的特定数据更新实体 [英] Doctrine/Symfony how to update entity with specific data from array
问题描述
我走了很久没有运气。我的情况是我有一个较大的表+60列,该列以 Doctrine实体表示。在FosREST上工作,我想要实现的是我想发送包含特定数据的JSON,例如
I have looking around for too long with no luck. My situation is that i have a bit large table +60 columns which is represented in Doctrine Entity. Working on FosREST and what i want to achieve is that i want to send a JSON with specific data let's say for example
[phone] => new_phone
[name] => new_name
[id] => 1
而我说该实体包含60多个列,例如地址,图片,类别等。
while like i said the entity contains over 60 columns like address, picture, category, etc...
和电话,姓名和ID并不是我每次都要更改的内容,但我想每次更改一些列。
因此,有时我可能想更新手机并命名,而第三次我想更改类别,我想更改类别和照片并指定地址
,所以有这样的东西吗?
and the phone, name and id are not what I want to change every time but i want to change some columns each time. So at some time i might want to update phone and name other time i want to change the category third time i want to change category and photo and address so is there anything like this ?
$entity->update($parameters);
其中的$参数如前所述动态变化。
ps。我知道我可以使用类似的东西构建一个很长的函数
where the $parameters are dynamically changed as explained before. ps. i know that i can build a very long function with something like
if(isset($parameters['name']){
$entity->setName($parameters['name']);
}
但如果有60个ifs,这听起来像是愚蠢的话,还有其他方法吗?
谢谢
but with 60 ifs this just sounds idiotic anyone have any other approach ? Thanks
推荐答案
1)如果参数是根据属性命名的(此处带有下划线注释),则可以执行此操作
1) If the parameters are named after the attributes (here with underscore annotations), you can do this
use Doctrine\Common\Util\Inflector;
// ...
public function setParameters($params) {
foreach ($params as $k => $p) {
$key = Inflector::camelize($k);
if (property_exists($this, $key)) {
$this->$key = $p;
}
}
return $this;
}
2)与二传手相同的事情
2) Same thing with the setters
use Doctrine\Common\Util\Inflector;
// ...
public function setParameters($params) {
foreach ($params as $k => $p) {
$key = Inflector::camelize($k);
if (property_exists($this, $key)) {
$this->{'set'.ucfirst($key)}($p); // ucfirst() is not required but I think it's cleaner
}
}
return $this;
}
3)如果名称不同,则可以执行以下操作:
3) If its not the same name, you can do this :
public function setParameters($params) {
foreach ($params as $k => $p) {
switch $k {
case 'phone':
$this->phoneNumber = $p;
break;
// ...
}
}
return $this;
}
编辑:最好的方法是第二个方法,但您应该定义一个白名单或列入黑名单,以避免用户更新您不希望他进行的操作。
EDIT : Best approach is number two but you should define a white-list or a black-list in order to avoid the user updating something you don't want him to.
这篇关于主义/ Symfony如何使用数组中的特定数据更新实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!