Search code examples
zend-frameworkzend-db

Using the CASE function in MYSQL with Zend_DB_Expr


I'm stuck with the following problem. In my product table i've two columns

Date_start and Date_end (both of them are a DATE datatype in my table).

I want to check if the current date is between the Date_start and Date_end then the status must be 'not available', else it must have the status 'available'.

How can I fix that in Zend_Db_Expr?

I've now the following query.

$getProducts = $this->oSelect
                            ->from(array('p'=>'producten'))
                            ->columns(array('link' => "CONCAT('/t/', p.titel_key)"))
                            ->joinLeft(array('c'=>'categorie'),'p.categorie_id = c.id',array('cat_titel'=>'c.titel'))
                            ->joinLeft(array('sc'=>'subcategorie'),'p.subcategorie_id = sc.id', array('subcat_titel'=>'sc.titel'))
                            ->where('p.online = 1');

Solution

  • In your columns:

    ->columns(array('link' => "CONCAT('/t/', p.titel_key)",
      'status' => new Zend_Db_Expr("...")))
    

    The 'CASE' should look something like this (i split it out for readability);

    CASE WHEN p.Date_end < NOW() AND p.Date_start > NOW() 
    THEN 'not available' ELSE 'available' END
    

    Zend_Db_Expr will take anything you give it and use it literally. Just remember that any DB specific commands might break if for some reason you switch systems.