Search code examples
phppropel2

Propel2 Build Query with functions and then call Find


Few days into PHP here and I have one that has me really stumped. I am using Propel2 to retrieve rows from a database based on filters the user selects. Ultimately I am hoping to have a lot of filters the user can select, and then generate a custom Propel2 call to retrieve the records. I can't use If/Then due to the exponential number of possible queries. However every approach to my example below has failed for me.

$dealfinder = DealsQuery::create()->filterByStillvalid(1)->orderByInception('DESC');

if(isset($dept)) {
    $dealfinder->filterByCategory($dept);
}

if (isset($early)) { 
    $oneHourAgo = date('Y-m-d H:i:s', strtotime(date('Y-m-d H:i:s'))- $dealDelay);
    $dealfinder->filterByInception(array('max' => $oneHourAgo ));   
}

$dealfinder->paginate($page = $pageNum, $maxPerPage = $maxColumn*$maxRow);

The code above returns:

deals.stillvalid=:p1, deals.inception<=:p1

This may just be a PHP function chaining syntax thing, so here is what a working Propel2 call would look like:

$dealfinder = DealsQuery::create()->filterByStillvalid(1)->filterByCategory($dept)
->orderByInception('DESC')->filterByInception(array('max' => $oneHourAgo ))
->paginate($page = $pageNum, $maxPerPage = $maxColumn*$maxRow);

I would be very grateful for help with this. Thank you.


Solution

  • I've had a similar issue and ended up moving the initial query inside the if statement. It's probably not the best solution until something cleaner but it's done the trick for me.

    if(isset($dept)) {
        $dealfinder = DealsQuery::create()
            ->filterByCategory($dept)
            ->filterByStillvalid(1)
            ->orderByInception('DESC');
    }
    
    if (isset($early)) { 
        $oneHourAgo = date('Y-m-d H:i:s', strtotime(date('Y-m-d H:i:s'))-$dealDelay);
    
        $dealfinder = DealsQuery::create()
            ->filterByInception(array('max' => $oneHourAgo ))
            ->filterByStillvalid(1)
            ->orderByInception('DESC');
    }
    
    $dealfinder->paginate($page = $pageNum, $maxPerPage = $maxColumn*$maxRow);