php 教义中的 findByExample

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2056884/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 04:50:15  来源:igfitidea点击:

findByExample in Doctrine

phpormdoctrine

提问by rizidoro

Is there a method in Doctrinelike Hibernate's findByExamplemethod?

Doctrine 中是否有类似HibernatefindByExample方法的方法?

thanks

谢谢

回答by Nikola Petkanski

You can use the findBymethod, which is inherited and is present in all repositories.

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

Example:

例子:

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

You can create findByExamplemethod in one of your repositories using a definition like this:

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

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

In order for this to work, you will have to create your own base class for the entities, implementing the toArraymethod.

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

MyEntitycan also be an interface, which your specific entities will have to implement the toArraymethod again.

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

To make this available in all your repositories, ensure that you are extending your base repository class - in this example, the MyRepositoryone.

要使其在您的所有存储库中可用,请确保您正在扩展您的基本存储库类 - 在本例中,是MyRepository一个。

P.S I assume you are talking about Doctrine 2.x

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

回答by Travis

Yes.

是的。

Let's say you have a model called Users. You have the following two classes

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

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

class User extends Base_User
{

}

in some other object you can do

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

$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"));