cphalcon icon indicating copy to clipboard operation
cphalcon copied to clipboard

[NFR]: Mvc\Model\Resultset: Allow traversal by primary key

Open Chealer opened this issue 4 years ago • 0 comments

Is your feature request related to a problem? Please describe. Yes When a model's find() method returns several records, it can be inconvenient to access specific records even with the primary key. I am new to Phalcon, but unless I'm missing something, here is what I had to do, for example, to retrieve the titles of a set of documents:

$documentsArray = $pages->items->toArray();
$titleRecords = Documents::find([
    'conditions' => 'uid in ({ids:array})',
    'bind' => ['ids' => array_column($documentsArray, 'uid_document')]
    ]);
$titles = [];
foreach ($titleRecords as $document) {
    $titles[$document->uid] = $document->title;
}
foreach ($documentsArray as &$documentArray) {
    $documentArray['document_title'] = $titles[$documentArray['uid_document']];
}

Describe the solution you'd like It would be much more convenient if Mvc\Model\Resultset could be browsed not just with 0-based indices, but using at least primary keys, so that - for example - the above could be simplified to just something like:

$documentsArray = $pages->items->toArray();
$titleRecords = Documents::find([
    'conditions' => 'uid in ({ids:array})',
    'bind' => ['ids' => array_column($documentsArray, 'uid_document')],
    ], Model::INDEX_PRIMARY);
foreach ($documentsArray as &$documentArray) {
    $documentArray['document_title'] = $titleRecords[$documentArray['uid_document']];
}

For me, it is code simplicity/readability which matters. I am not worried about the performance of traversal for this case.

Describe alternatives you've considered Introducing a new method to complement find() (something like findByPrimaryKey()) could be just as good as adding an argument to find().

Chealer avatar Jul 21 '21 20:07 Chealer