Love Fuel?    Donate

FuelPHP Forums

Ask your question about FuelPHP in the appropriate forum, or help others by answering their questions.
"Dynamic" conditions in ORM model relations
  • I have seen a solution* proposed by Jelmer Schreuder on stackoverflow where he proposes to add the condition in an _init function in the model like this :

    public static function _init()
    {
        $culture_id = ; // get that from somewhere
        static::$_has_one['locale']['where'][] = array('CultureId', '=', $culture_id);
    }

    This solution works fine as long as you fetch the related object from an already instanciated parent like :
    $page = \Model_Page::find(5);
    $page->locale;
    or
    $page = \Model_Page::query()->where('id',5)->get_one();
    $page->locale;

    But this doesn't work if you load the parent and the related object from a single query :
    $page = \Pages\Model_Page::query()->where('id',5)->related('locale')->get_one();

    This last query throw a Database_Exception because it expects to get a join condition (escaped by ``) on a field and not on a value :
    …LEFT JOIN `locale` AS `t1` ON (`t0`.`id` = `t1`.`page_id` AND `t1`.`CultureId ` = `1`)

    Does anyone have a suggestion to this problem ?

    [UPDATED] :
    This error only occurs with $culture_id being a number. If it is a string the last query does escape properly the value with '' :
    …LEFT JOIN `locale` AS `t1` ON (`t0`.`id` = `t1`.`page_id` AND `t1`.`CultureId ` = 'fr')

    I found a workaround by adding slashes to $culture_id but this might still be a real issue.

    * The whole story of the solution proposed by Jelmer is available here :http://stackoverflow.com/questions/8664089/can-fuelphp-orm-handle-this-database-design/8703858#8703858
  • HarroHarro
    Accepted Answer
    If you want to pass a literal to a query, encapsulate it in a DB::expr(), to prevent it from being escaped.
  • Ok, thanks Harro.

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

In this Discussion