Question

I am trying out active record. I believe it's a great ORM however I am having trouble getting it to run.

Some of the methods work but others don't For example

<?php
$user=new user();
foreach(user::find('all') AS $row) {
  echo "$row->username <br>"; //this works fine. 
}

However when options are supplied or validates_uniqueness_of is used, an exception is thrown:

foreach (user::find('all','order'=>"created DESC ,'limit'=>10")) {
  echo "$row->username <br>";

This results in

Fatal error: Uncaught exception 'ActiveRecord\RecordNotFound' 

... with message ...

Couldn't find all user with IDs (all,created DESC ,'limit'=>10) (found 0, but was looking for 2)

I am using php 5.3.4 and using nightly build (May 8 2013) Please advise on how to fix this.

/*------------------------edit : full code----------------*/

$path_to_AR = "AR/";
include $path_to_AR . "activerecord.php";
ActiveRecord\Config::initialize(function($cfg) {
    $cfg->set_model_directory('model');
    $cfg->set_connections(
                    array(
                     'development' => 'mysql://root:asdf@localhost/test_ar',
                     'test' => 'mysql://username:password@localhost/test_database_name',
                     'production' => 'mysql://username:password@localhost/production_database_name'
                    )
            );
        });   

$user = new user(); //class user extends ActiveRecord\Model {}

foreach (user::find(array('all','conditions'=>"username LIKE '%ohn%'")) AS $row) {
    echo "Username:$row->username<br>";
}
Était-ce utile?

La solution

The problem is that you're calling the methods in a wrong way.

The first parameter signify a type of search, and should be a string (but you can actually use shortcut methods: User::all() instead of User::find('all'), for example), but the second parameter should be an array. So it should be written like this:

user::find('all', array('order' => 'created DESC', 'limit' => 10));

... or just ...

user::all(array('order' => 'created DESC', 'limit' => 10));

My guess (as you still didn't provide the whole code) is that you're actually wrap all the params of find into a single array. And this method is tuned up so that in such cases it attempts to use the values of this array as IDs to be used in the table look-up.

The number of these IDs is 2, so it expected to find 2 items - but obviously can't find any; hence an Exception. The same approach is used by Ruby-On-Rails implementation; check this discussion for a similar error (and the cause).

Check the documentation for more details on how finder methods of PHPActiveRecord should be used.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top