2016-11-30 27 views
1

任何人都可以告訴我如何使用輸入'findby'作爲對象數組? 我有這樣的代碼:如何使用輸入爲數組的「findby」原則?

public function getIpOnline($acc) 
{ 
    try {      
     $rs = $this->em 
      ->getRepository($this->target) 
      ->findBy(array('login' => $acc)) 
     ; 
    } catch (Exception $e) {   
     echo "ERROR ".$this->target." DAO: ".$e; 
    }    
    var_dump($rs);exit(); 
    return $rs;  
} 

我得到了錯誤:

Catchable fatal error: Object of class Character could not be converted to string in /var/www/xxx.com/vendor/doctrine/dbal/lib/Doctrine/DBAL/Driver/PDOStatement.php on line 67 

在此先感謝。

回答

2

$this->target可能是一個對象,但您必須返回對象類的名稱。

您是否嘗試過使用get_class

或者更簡單地說Character::class :)

就像你問,這是get_class您的例子:

public function getIpOnline($acc) 
{ 
    $nameClass = get_class($this->target); 

    try { 
     $rs = $this->em 
      ->getRepository($nameClass) 
      ->findBy(['login' => $acc]); 
    } catch (Exception $e) { 
     echo 'ERROR ' . $nameClass . ' DAO: ' . $e; 
    } 
    die(var_dump($rs)); 

    return $rs; 
} 
+0

可以ü請詳細告訴我?我不明白。 – Hanata

+0

@Hanata在函數getRepository($ repoName);你必須傳遞實體的類名稱。例如你可以輸入'Product \ Entity \ Phone',或者使用函數get_class($ object),或者使用Product :: class。所有這些知識將返回具有類/對象名稱空間的完整類名稱。 – Maytyn

0

你能做到這一點只有在情況下,當你的實例$name有魔術方法__toString

福克斯例如:

class Name 
{ 
    public function __toString() 
    { 
     return 'ipad'; 
    } 
} 

$name = new Name(); 
$product = $entityManager->getRepository('Product')->findBy(['name' => $name]); 
0
public function getIpOnline($acc) 
{ 
try {      
    $rs = $this->em->getRepository($this->target)-findBy(['login' => $acc)); 

/* or u can also use findOneBy if expecting result is a single record and find corresponding data only based in $acc 
    $rs = $this->em->getRepository($this->target)-findOneByLogin($acc); 
*/ 

} catch (Exception $e) {   
    echo "ERROR ".$this->target." DAO: ".$e; 
}    
var_dump($rs);exit(); 
return $rs;  

}

也看到http://symfony.com/doc/current/doctrine.html#fetching-objects-from-the-database