Help Sorting One-to-Many

I have a table "business". Each business has many businessPromos (a one-to-many relationship). A businessPromo has a createtime. How can I order a query for businesses by the createtime of the first businessPromo of each business? (I have the businessPromos for each business ordered by createtime DESC)


I would suggest this:

  1. make a new statistical relation ‘firstPromo’ to get the first businessPromo for each business (

  2. use that relation in the query


This works well for fetching and displaying the date of first businessPromo but you probably can’t order the result by stat relation.

It seems to be far from trivial but findAllBySql() may work (not tested):


	'SELECT * FROM business t1


		SELECT t2.business_id, t2.createtime

		FROM businessPromo t2

		LEFT JOIN businessPromo t3

		ON t2.business_id = t3.business_id AND t2.createtime > t3.createtime


	) t4 ON = t4.business_id

	ORDER BY t4.createtime'


I don’t know if it can be done by CDbCriteria.

You can simply add the sort in the criteria:


Just check in the log that the alias t4 is given to the right table.