简体   繁体   中英

Looping over results with MongoDB and Lithium

I've just started using Lithium and have come across a (probably very simple...) problem where I can't iterate over the results of a simple query. I have compared my code to various samples and I can't see any differences but something must be!

// Controller
namespace app\controllers;

use app\models\POI;

class POIsController extends \lithium\action\Controller {

    public function index($category) {

       $data = POI::find('all', array('limit' => 10));

       $this->set(array('data' => $data));
    }
}



// Model
namespace app\models;

class POI extends \lithium\data\Model {
    protected $_meta = array(
        'source' => 'POI'
    );
}



// View
print $data->count(); // outputs 10

foreach($data as $poi):?>
    <?php print $poi->Name;?>
<?php endforeach; ?>

The loop in the View only displays the first item's Name field and misses out the other 9 which are apparently there.

Does anyone have any ideas about why this is happening?

As always the answer pops up just after asking the question...

My model doesn't have the usual ID set up (it has key in field "ID") so I had to add that to the schema and the meta data otherwise I guess all the models were thought to have the same empty key and so wouldn't iterate.

Updated Model code:

namespace app\models;

class POI extends \lithium\data\Model {
    protected $_meta = array(
        'source' => 'POI',
        'key' => 'ID'
    );

    public $_schema = array(
        'ID' => array('type'=>'id'),
        'Name' => array('type'=>'string','null'=>false)
    );

}

Hope this can help someone else in the future!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM