PHP Lithium: Filtering an existing DocumentSet and getting the first match

I am fetching DocumentSet in lithium from MongoDB but I don't want to process documents right away. Instead, I would like to have a filter that I could say something like this:

$manyDocuments->giveMeTheOneWhere(array('foo' => 'bar'));

      

I already tried this but it didn't work:

$manyDocuments->find(function($singleDocument){
    return ($singleDocument->foo == 'bar');
});

      

Even if I manually return true inside the closure, it always returns an empty DocumentSet.

Just to be clear: I'm not looking for a database job, I want to get one of the pre-existing DocumentSet instead. Is there a fancy way to achieve this, or do I need to iterate with a custom function?

+3


source to share


3 answers


Instead of using, find()

I just used first()

with closure. This works as expected. Unfortunately, this was the only one that I have not tried before. Excuse me for answering my own question.



In any case, I will still be interested in a way to get another Install document .

0


source


This looks right to me. Is this the exact code you are using?
For example, is the value "bar" you are using what you are passing through?



+2


source


I'm on the latest of the lithium master branch and wrote this unit test that works for me. I'm not sure why you are getting an empty DocumentSet.

$docs = new DocumentSet(array('data' => array(
    new Document(array('data' => array(
        'id' => 1,
        'foo' => 'bar'
    ))),
    new Document(array('data' => array(
        'id' => 2,
        'foo' => 'baz'
    ))),
    new Document(array('data' => array(
        'id' => 3,
        'foo' => 'bar'
    ))),
    new Document(array('data' => array(
        'id' => 4,
        'blah' => 'ack'
    )))
)));
$filtered = $docs->find(function($doc) {
    return $doc->foo === 'bar';
});
$expected = array(
    '0' => array('id' => 1, 'foo' => 'bar'),
    '2' => array('id' => 3, 'foo' => 'bar')
);
$this->assertIdentical($expected, $filtered->data());

      

+1


source







All Articles