我环顾四周太久没有运气.我的情况是我有一个有点大的表 +60 列,它在 Doctrine Entity 中表示.在 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...
电话、姓名和身份证不是我每次都想更改的,但我每次都想更改一些列.所以有时我可能想更新电话和姓名,其他时候我想第三次更改类别我想更改类别和照片和地址有这样的吗?
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);
$parameters 如前所述动态更改.附:我知道我可以用类似的东西构建一个很长的函数
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 DoctrineCommonUtilInflector;
// ...
public function setParameters($params) {
foreach ($params as $k => $p) {
$key = Inflector::camelize($k);
if (property_exists($this, $key)) {
$this->$key = $p;
}
}
return $this;
}
2) 与 setter 相同
2) Same thing with the setters
use DoctrineCommonUtilInflector;
// ...
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.
这篇关于Doctrine/Symfony 如何使用数组中的特定数据更新实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!