sittercity/sprig

HasOne not loading the requested record

Closed this issue · 5 comments

I have a problem with HasOne not loading the requested record. I've tried to ask for help in the Kohana forum to find out if it's a real issue or not, but no solutions came. Here's an example.

Models:

class Model_Color extends Sprig {

    protected $_table = 'colors';

    protected function _init()
    {
        $this->_fields += array(
            'id' => new Sprig_Field_Auto(array(
                'primary' => TRUE,
            )),
            'name' => new Sprig_Field_Char(),
            'detail' => new Sprig_Field_HasOne(array(
                'model' => 'Detail',
            )),
        );
    }

} // End Model_Color

class Model_Detail extends Sprig {

    protected $_table = 'details';

    protected function _init()
    {
        $this->_fields += array(
            'id' => new Sprig_Field_Auto(array(
                'primary' => TRUE,
            )),
            'color_id' => new Sprig_Field_BelongsTo(array(
                'model' => 'Color',
            )),
            'code' => new Sprig_Field_Char(),
            'example' => new Sprig_Field_Char(),
        );
    }

} // End Model_Detail

In this example the "colors" table would contain the name of colors, e.g. blue, and the details table would contain some details for these colors, the "code" field is the color code for CSS, the "example" field is used to give an example for the color, e.g. the example for blue is sky.

Query in the controller:
$color = Sprig::factory('Color')->values(array('id' => '2'))->load();
echo $color->detail->load()->example;

The result of this would be always the same, which is the very first record of the "details" table, no matter which record I'm loading from the "colors" table.

Sprig runs this SQL query when echoing out the "example" field:
SELECT details.id, details.color_id, details.code, details.example FROM details LIMIT 1

Your field name should be color not color_id... and don't use a column value (not yet supported).

Thanks!

@shadowhand: I might be doing something wrong, but I'm still running into problems. I did what you suggested and it does solve my problem, but only for the first query.

If I do:
$color = Sprig::factory('Color')->values(array('id' => '2'))->load();
echo $color->detail->load()->example;
echo $color->detail->load()->code;

Echoing out the "example" field returns what I wanted, but the "code" field returns data from the first record of the "details" table. So, the first echo is always what I wanted and from the second echo it always falls back to the first record of the "details" table (this means if I change the order of the echos then I would get the "code" field right).

In this example the SQL query for the "code" field is missing the WHERE statement and it isn't an instance of HasOne.

You only call load() once:

$detail = $color->detail->load();
echo $detail->example;
echo $detail->code;

Thanks a lot! :)