【问题标题】:How can I search for value in entity by column name?如何按列名在实体中搜索值?
【发布时间】:2019-09-25 16:36:46
【问题描述】:

我正在尝试按列名在表格行中查找值:

$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;
     }
  }

这里的错误信息是:

在渲染模板期间引发了异常 (“可捕获的致命错误:App\Entity\Documents 类的对象可能 不能转换成字符串”)。

我只是很难找到实现我想要的正确方法。

【问题讨论】:

    标签: arrays symfony object variables entity


    【解决方案1】:

    尝试使用variable function

    $myvariable = "getCat";
    $result = $entity->$myvariable();
    

    【讨论】:

    • 我这样做了$myvariable= "get".$name;$getObj = (string) $myvariable; $result = $entity->$getObj();
    【解决方案2】:

    您可以尝试通过反射来做到这一点。这里简单的例子

    <?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))}();
    

    【讨论】:

    • 哇,这太复杂了。没有简单的解决办法?
    • 用一个更简单的例子更新了答案。反射是一个有趣的东西,你应该阅读它。
    猜你喜欢
    • 2012-10-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-07
    • 2011-12-07
    • 2018-06-22
    • 2019-01-04
    • 1970-01-01
    相关资源
    最近更新 更多