Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get extra columns when hydrating Propel objects with custom SQL?

Tags:

php

mysql

propel

I am using custom SQL to join two tables, apply some business logic to dates, then use the results to hydrate a propel object (collection). Here's my code:

$testtypes = TesttypeQuery::create()->find();

foreach ($testtypes as $testtype) {

  /* work out what most recent schedule */
  $con = \Propel::getConnection(SchedulePeer::DATABASE_NAME);
  $sql = "SELECT `schedule`.*, (`schedule`.`last` + INTERVAL `duration`.`weeks` WEEK + INTERVAL `duration`.`months` MONTH + INTERVAL `duration`.`years` YEAR) AS `dueDate` FROM `schedule` LEFT JOIN `duration` ON `schedule`.`duration_id` = `duration`.`id` HAVING `schedule`.`testtype_id` = {$testtype->getId()} AND `dueDate` < NOW() ORDER BY `dueDate` ASC LIMIT 1";
  $stmt = $con->prepare($sql);
  $stmt->execute();
  $formatter = new \PropelObjectFormatter();
  $formatter->setClass(SchedulePeer::OM_CLASS);
  $schedules = $formatter->format($stmt);

  // more stuff here ... 
}

This question comes in several parts, because there might be a completely better way of doing this - so please feel free to make suggestions other than just answering my specific questions:

  • I am using HAVING instead of WHERE so that I can use the aliased column dueDate, which I want to use as part of the check and order, as well as returning it as part of the result-set to use later. Is there a way to grab this value but still hydrate the propel object? When I use fetch() or other PDO methods on $stmt I can no longer use this with the call to format().
  • Alternatively is there a better way to do this with pure Propel?
like image 220
LeonardChallis Avatar asked Nov 07 '12 11:11

LeonardChallis


1 Answers

You should add some steps. This is the logical process:

  1. SQL call that does not include the extra columns
  2. Hydrate the object(s)
  3. SQL call the returns values for the extra columns
  4. Update the hydrated object(s) with the extra column values

Hope this helps. Cheers.

like image 176
Tarzan Avatar answered Oct 17 '22 12:10

Tarzan