在另一个表中具有条件的Phalcon模型find() [英] Phalcon Model find() with condition in another table

查看:80
本文介绍了在另一个表中具有条件的Phalcon模型find()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有2张这样的桌子

so I have 2 tables like this

books
id        name       status_id
-------------------------------
1         a          0
2         b          2
...

status
id        description
---------------------
0         borrowed
1         available
2         lost

Phalcon模型

class Books extends ModelBase {

    public function initialize() {
        $this -> belongsTo("status_id", "Status", "id");
    }
}

class Status extends ModelBase {
    public function initialize() {
        $this -> hasMany('id', "Books", 'status_id');
    }
}

我想提取所有状态描述为丢失"的图书.这是我到目前为止的内容:

I would like to extract all books that has status description "lost". This is what I have so far:

$lostBooks = Books::find(
    'conditions' => "description=:status:",
    'bind' => array(
        'status' => 'lost'
    ),
);

更新: 通过解决方法,我得到了想要的东西

Update: I got what I want through a workaround

$lostStatus = Status::findFirst("description='Closed'");
$lostBooks = Books::find(
    'conditions' => "status_id=:id:",
    'bind' => array(
        'id' => $lostStatus -> id
    ),
);

但是我觉得我没有按照预定的方式执行此类任务,因此,如果您有更好的任务,请在下面回答.

However I feel like I'm not using the intended way to execute these kind of tasks, so if you have a better one, please answer below.

推荐答案

您可能有两种方法:

直接从模型中加入很难实现.这就是设计queryBuilder的原因-例如,仅当您愿意获取数据时,模型才查询数据.通过访问假定加入的$books->getStatus().有关更多信息,请搜索文档:请轻巧示例.在SO的上有一个有用的话题,因此您将知道为什么不总是直接进行优化使用模型是个好主意.

Joins directly from models are hard to achieve. It's why queryBuilder was designed - models are querying for data only if you are willing to get them, eg. by accessing supposedly-joined $books->getStatus(). For more information search documentations: hudge example. There was also an useful topic about optimisations here on SO, so you will know why not always direct usage of models is good idea.

要使其变得简单,清晰,但也许不是大多数性能(取决于使用情况),因为不久前(Phalcon 1.3.2?),您可以使用

To make it easy, clear but maybe not most performance-wise (depends on usage), since not long ago (Phalcon 1.3.2?) you can create a separate model with additional conditions in it (not tested example):

class LostBooks extends Books {

    public function initialize() {
       $this -> belongsTo("status_id", "Status", "id",
       [
            'alias' => 'status',
            'params' => [
                'description' => 'lost'
            ]
       ]);
    }
}

在正确声明的情况下,您可以通过以下方式简单实现

With that properly declarated you can get those simple by

$lostBooks = LostBooks::find();

PS:如果您以前使用PHP 5.4,请养成一些习惯.请使用array()代替[].

PS: use array() instead [] of, if you are previous to PHP 5.4, got some habits.

这篇关于在另一个表中具有条件的Phalcon模型find()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆