Love Fuel?    Donate

FuelPHP Forums

Ask your question about FuelPHP in the appropriate forum, or help others by answering their questions.
How to look at SQL code generated by Orm\Model?
  • I spent a long time to fix errors in my query but at the end It become working wrong without any errors. And I would see the SQL code, that was generated with my query using Orm\Model.

    How can I do this?
  • philipptempelphilipptempel
    Accepted Answer
    // Run a query e.g.,
    $query = \Model\User::query()->related('group')->get();
    // Then echo the result
    echo \DB::last_query();
    There's also a way using, but maybe @Harro Verton can tell us more about that (I never used it and from the code I cannot get it to work as wanted)
    $query = \Model\User::query()->related('group');
    echo $query->build_query();
  • HarroHarro
    Accepted Answer
    Or enable the profiler, and enable db profiling in your db definition. It not only shows you the SQL, but also the performance, the result, and the analysis (only for MySQL backends).

    @philliptempel,

    you mean get_query() ? That will return a Database_Query object, that you can cast to string to get the SQL generated for that object.
  • Thank you, Philip and Harro.
  • @Harro, yes, that's what I meant. I never explicitly used get_query() and build_query() but I ran across them because I wanted to debug queries before they're actually executed. That's when I dug into the code but couldn't wrap my head around the arguments to the function.

    Your suggested way is probably the better nevertheless.
  • I am writing my own CMS and making users grid based on w2ui grid. It sends some complicated restful requests (in part of filtering), because I have write some muss logic with ->where() and ->or_where() and replacing requested operator with real SQL operator, e. g.:

    switch ($operator) {
                case 'contains':
                    $operator = 'like';
                    $value = '%'.$value.'%';
                    break;
                case 'is':
                default:
                    if (!is_null($value)) $operator = '=';
    }

    Lost 'break;' cause that implicit wrong logic, where $value replaced with '%'.$value.'%', but 'contains' replaced with '=' instead of 'like'.

    I just looked at SQL statement and instantly found my mistake. Thank you again :)
  • @philipptempel,

    build_query() isn't intended to be called from "userland", and get_query() doesn't have any arguments, you use it where you would normally use get() or get_one(), to get the query object instead of the query result.

Howdy, Stranger!

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

In this Discussion