Love Fuel?    Donate

FuelPHP Forums

Ask your question about FuelPHP in the appropriate forum, or help others by answering their questions.
ORM - Chained query help
  • I'm trying add a 'where' clause to a query based on an incoming get variable but having problems.  The below example seems like it should work but outputs all the events, not just the first when the 'status' variable is set to 'first'.  Any ideas?  

    public function action_test() {

    $status = Input::get('status');
    // Start query
    $query =  Model_Events::query();
    // Add appropriate where clause to query
    if ($status == 'first') {
    $query->where('id', '1');
    } else {
    $query->where('id', '2');
    // Execute query
    $query = Model_Events::query()->get();

    // Typecast the query results to an array for output
    $output = (array) $query;
    return $output;
    }
  • Update:  I figured out a way to do it but I'm not sure if it's the right or only way.  Would still like some input on this.

    Here's what I did:

    Above, at the "// Execute query" section, change it to

    $query_out = $query->get();

    Now the $query_out object contains the executed query result.


  • When you call Model_Whatever::query(), a new instance of Orm\Query is returned. So $query = Model_Events::query()->get(); overwrites the previously created and filtered Query instance. $query->get() is the right way.
  • sagikazarmakr, yes, the original post was instantiating the ORM twice.  My second post addressed it and contains the fix.  I expected the the example below to output the contents of the query ...it doesn't.  I spent a lot of time trying to figure this out and thought I'd share.  (This could be useful to others in the FUELPHP ORM documentation).

    DOES NOT WORK:
    $query =  Model_Events::query();
    $query->where('id', '1');
    $query->get();
    print_r ($query);


    WORKS :
    $query =  Model_Events::query();
    $query->where('id', '1');
    $output = $query->get();
    print_r ($output);


  • http://fuelphp.com/docs/packages/orm/crud.html#/find_chaining

    There are several examples about the use of query and get.

    Also, you can't blame your query object it does not overwrite itself with your fetched data. :D

    After executing the query, you can still use your query object for counting results, etc.

Howdy, Stranger!

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

In this Discussion