如何按列名搜索实体中的值?
How can I search for value in entity by column name?
我试图在我的 table 行中按列名称查找一个值:
$entity = $this->getDoctrine()->getRepository($EntityName)->findOneBy(['uuid' => $uuid]);
$result = $entity->getCat();
困难在于,我希望能够用变量替换 "Cat"。
不幸的是,这是不可能的:
$myvariable = "Cat";
$result = $entity->'get'.$myvariable.();
所以我采用了另一种方法:
$entity = $this->getDoctrine()->getRepository($EntityName)->findBy(array('uuid' => $uuid));
$result = array_search($myvariable, $entity);
但是这里我得到一个空输出。
另一种方法:
foreach ($entity as $key => $value) {
if($myvariable == $key){
$result = $value;
}
}
这里的错误信息是:
An exception has been thrown during the rendering of a template
("Catchable Fatal Error: Object of class App\Entity\Documents could
not be converted to string").
我只是很难找到实现我想要的目标的正确方法。
你可以试着用反射来做到这一点。这里简单的例子
<?php
class ClassName
{
private $property1;
private $property2;
public function __construct($property1, $property2)
{
$this->property1 = $property1;
$this->property2 = $property2;
}
public function getProperty1()
{
return $this->property1;
}
public function getProperty2()
{
return $this->property2;
}
}
$class = new ClassName('test1', 'test2');
$field = 'property2';
$reflectionClass = new \ReflectionClass($class);
if ($reflectionClass->hasProperty($field)) {
$property = $reflectionClass->getProperty($field);
$property->setAccessible(true);
echo $property->getValue($class);
}
// or
echo $class->{sprintf('get%s', ucfirst($field))}();
尝试使用 variable function:
$myvariable = "getCat";
$result = $entity->$myvariable();
我试图在我的 table 行中按列名称查找一个值:
$entity = $this->getDoctrine()->getRepository($EntityName)->findOneBy(['uuid' => $uuid]);
$result = $entity->getCat();
困难在于,我希望能够用变量替换 "Cat"。
不幸的是,这是不可能的:
$myvariable = "Cat";
$result = $entity->'get'.$myvariable.();
所以我采用了另一种方法:
$entity = $this->getDoctrine()->getRepository($EntityName)->findBy(array('uuid' => $uuid));
$result = array_search($myvariable, $entity);
但是这里我得到一个空输出。
另一种方法:
foreach ($entity as $key => $value) {
if($myvariable == $key){
$result = $value;
}
}
这里的错误信息是:
An exception has been thrown during the rendering of a template ("Catchable Fatal Error: Object of class App\Entity\Documents could not be converted to string").
我只是很难找到实现我想要的目标的正确方法。
你可以试着用反射来做到这一点。这里简单的例子
<?php
class ClassName
{
private $property1;
private $property2;
public function __construct($property1, $property2)
{
$this->property1 = $property1;
$this->property2 = $property2;
}
public function getProperty1()
{
return $this->property1;
}
public function getProperty2()
{
return $this->property2;
}
}
$class = new ClassName('test1', 'test2');
$field = 'property2';
$reflectionClass = new \ReflectionClass($class);
if ($reflectionClass->hasProperty($field)) {
$property = $reflectionClass->getProperty($field);
$property->setAccessible(true);
echo $property->getValue($class);
}
// or
echo $class->{sprintf('get%s', ucfirst($field))}();
尝试使用 variable function:
$myvariable = "getCat";
$result = $entity->$myvariable();