在Doctrine中的findByExample

riz*_*oro 14 php orm doctrine

是否有一种方法学说休眠findByExample方法是什么?

谢谢

Nik*_*ski 22

您可以使用该findBy方法,该方法是继承的并存在于所有存储库中.

例:

$criteria = array('name' => 'someValue', 'status' => 'enabled');
$result = $em->getRepository('SomeEntity')->findBy($criteria);
Run Code Online (Sandbox Code Playgroud)

您可以findByExample使用如下定义在其中一个存储库中创建方法:

class MyRepository extends Doctrine\ORM\EntityRepository {
    public function findByExample(MyEntity $entity) {
        return $this->findBy($entity->toArray());
    }
}
Run Code Online (Sandbox Code Playgroud)

为了使其工作,您必须为实体创建自己的基类,以实现该toArray方法.

MyEntity也可以是一个接口,您的特定实体必须toArray再次实现该方法.

要在所有存储库中提供此功能,请确保扩展基本存储库类 - 在此示例中为该类MyRepository.

PS我假设你在谈论Doctrine 2.x


Tra*_*vis 10

是.

假设您有一个名为Users的模型.您有以下两个类

abstract class Base_User extends Doctrine_Record 
{
   //define table, columns, etc
}

class User extends Base_User
{

}
Run Code Online (Sandbox Code Playgroud)

在其他一些对象中你可以做到

$user = new User;

//This will return a Doctrine Collection of all users with first name = Travis
$user->getTable()->findByFirstName("Travis");

//The above code is actually an alias for this function call
$user->getTable()->findBy("first_name", "Travis");

//This will return a Doctrine Record for the user with id = 24
$user->getTable()->find(24);

//This will return a Doctrine Collection for all users with name=Raphael and 
//type = developer
$user->getTable()
     ->findByDql("User.name= ? AND User.type = ?", array("Raphael", "developer"));
Run Code Online (Sandbox Code Playgroud)