Love Fuel?    Donate

FuelPHP Forums

Ask your question about FuelPHP in the appropriate forum, or help others by answering their questions.
Model query, ordered by db expression
  • I have a model "article" with the following fields:
    • id (int)
    • name (string)
    • image_name (string)
    • ...
    I have the base query:

    Now I want to get some rows of it, ordered by items where "image_name" is set and ordered by name ASC.

    I tried the following:

    $query = \Model_Article::select("*");
    $query->select(\Db::expr("(CASE WHEN bild IS NOT NULL THEN 1 ELSE 0 END) AS "_has_image"));

    Which throws an error. 

    The following didn't work, since the alias isn't correct, because it gets the normal "cXX" alias instead of the correct "
    _has_image":

    $query = \Model_Article::select("*");
    $query->select(array("_has_image" => \Db::expr("(CASE WHEN bild IS NOT NULL THEN 1 ELSE 0 END) AS "_has_image")));

    Is there a way, to add the following "select" column:

    (CASE WHEN image_name IS NOT NULL THEN 1 ELSE 0 END) AS _has_image

    so that I can use it in the $query->order_by(("_has_image" => "DESC". "name" => "ASC")

    ?

  • Ok, I have to use

    $query = \DB::select("*")
    ->select(\Db::expr("IF(img_name IS NULL or img_name = '', 0, 1) AS _has_img"))
    ->order_by("_has_img", "DESC")
    ->order_by("name", "ASC")
    ->from(\Model_Article::table())
    ->as_object("\\Model_Article")
    ->execute();

Howdy, Stranger!

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

In this Discussion