Question

I just installed a fresh copy of Kohana 3.2, built my database, wrote my first model, and tried testing it. Everything works fine except the model's "save" method is being executed twice--I end up with two new entries in the database instead of one. The problem only occurs when I use the "find" code shown below.

Why would the model's save get executed twice, once as expected and once because of the find?

Here's the code:

class Controller_Welcome extends Controller {

public function action_index()
{

    $rating = ORM::factory('rating');

    $rating->user_id = 1;
    $rating->userlevel_id = 3;
    $rating->category_id = 1;
    $rating->page_id = 1;
    $rating->rating = 4;
    $rating->comments = 'This one is a real killer';
    $rating->ratingstatus_id = 1;

    $rating->save();

    $found = ORM::factory('rating')
        ->where('id', '=', 1)
        ->find();

    $this->response->body($found->comments); // Test to check for found data
}

} // End Welcome

Thanks in advance!

Was it helpful?

Solution

There are two issues that were causing my problem:

  1. I didn't have a favicon.ico on my server. Many browsers request one, and all URLs that aren't actual files or directories get redirected to the index page. Every time I loaded the page, the browser would request a missing favicon and get redirected to my index page--two requests. After looking at my logs, this page was what tipped me off: http://forum.kohanaframework.org/discussion/7447/error-kohana_request_exception/p1

  2. After I added a favicon, I still saw the double request behavior occasionally. It turns out it was a behavior of Google Chrome--Chrome prefetches pages, so each time I changed the content, Chrome would prefetch and cache the page (adding a request).

After adding a favicon and when using a browser besides Chrome, everything behaves as expected.

OTHER TIPS

$rating = ORM::factory('rating');

This line represents nothing.

If you want to create new record you should use create() instead save().

$rating = new Model_Rating;

$rating->user_id = 1;
$rating->userlevel_id = 3;
$rating->category_id = 1;
$rating->page_id = 1;
$rating->rating = 4;
$rating->comments = 'This one is a real killer';
$rating->ratingstatus_id = 1;
$rating->create();

If you want to load single rating object with given id:

$found = ORM::factory('rating', 1);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top