Phalcon Model find() with condition in another table

房东的猫 提交于 2019-12-22 12:43:47

问题


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 models

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.


回答1:


You have possible two approaches:

1. Via queryBuilder

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.

2. Via creating a separate model

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: use array() instead [] of, if you are previous to PHP 5.4, got some habits.




回答2:


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', 
            array('alias' => 'books')
        );
    }

}

$lostBooks = Status::findFirst("description = 'lost'")->getBooks();

$lostBooks = Status::findFirst("description = 'lost'")->books;


来源:https://stackoverflow.com/questions/29840462/phalcon-model-find-with-condition-in-another-table

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!