在 Doctrine 模型中设置所需的值

发布于 2024-10-02 02:26:36 字数 172 浏览 0 评论 0原文

是否可以在 Doctrine 模型中设置约束,以便使用该模型的所有查询都包含此要求?例如,如果我有一个汽车模型,并且我想确保使用该模型检索到的所有结果都在数据库中设置了active = 1。我可以在每个单独的查询中定义它,但似乎可能有更好的方法。

干杯!

Is it possible to set a constraint in a Doctrine model, so that all queries using that model include this requirement? For example, if I have a Car model and I want to ensure that all results retrieved using the model have active = 1 set in the database. I could define this in each individual query, but it seems like there's probably a better way.

Cheers!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

飞烟轻若梦 2024-10-09 02:26:36

我会利用模型内令人惊叹的前钩和后钩。

示例:

class Model_Car extends Model_Base_Car
{
    public function preDqlSelect(Doctrine_Event $event)
    {
        $event->getQuery()->addWhere("active = ?", 1);
    }
}

虽然我没有对此进行测试,但它应该可以工作。我过去经常使用前钩和后钩来让我的生活更轻松。例如,我有一个模型想要在每次插入和更新时保存 REMOTE_ADDR,因此我执行了以下操作以使我的生活更轻松:

class Model_Example extends Model_Base_Example
{
    public function preInsert(Doctrine_Event $event)
    {
        $this->created_ip = $this->_getRemoteIp();
    }

    public function preUpdate(Doctrine_Event $event)
    {
        $this->updated_ip = $this->_getRemoteIp();
    }

    protected function _getRemoteIp()
    {
        return ip2long($_SERVER['REMOTE_ADDR']);
    }
}

希望这会有所帮助!

I would take advantage of their amazing pre and post hooks inside the model.

Example:

class Model_Car extends Model_Base_Car
{
    public function preDqlSelect(Doctrine_Event $event)
    {
        $event->getQuery()->addWhere("active = ?", 1);
    }
}

Although I did not test this, it should work. I have used the pre and post hooks a lot to make my life easier in the past. For instance, I had a model that wanted to save the REMOTE_ADDR on each insert and update, so I did the following to make my life easier:

class Model_Example extends Model_Base_Example
{
    public function preInsert(Doctrine_Event $event)
    {
        $this->created_ip = $this->_getRemoteIp();
    }

    public function preUpdate(Doctrine_Event $event)
    {
        $this->updated_ip = $this->_getRemoteIp();
    }

    protected function _getRemoteIp()
    {
        return ip2long($_SERVER['REMOTE_ADDR']);
    }
}

hope this helps!

遗忘曾经 2024-10-09 02:26:36

我会在查询 ->andWhere('active = ?', 1) 中执行此操作,但如果您尝试采用这种“棘手的方式”,您始终可以构建自己的水化器。

I would do this in query ->andWhere('active = ?', 1), but if you are tring to do this "tricky way", you can always build your own hydrator.

丑丑阿 2024-10-09 02:26:36

这是您问题的答案:对学说查询对象进行子类化。

http://brentertainment.com/2010/03/ 03/doctrine_query_extra-扩展-doctrine-query-object/

here is an answer to your question: subclassing the doctrine query object.

http://brentertainment.com/2010/03/03/doctrine_query_extra-extending-the-doctrine-query-object/

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文