user125661
user125661

Reputation: 1568

When using an extbase query, can I order the results by a field in a linked model?

I am querying a Model*, which has a field that refers to another Model. Is it possible to order the results using a field in the linked Model?

So for example:

Car contains a field which refers to its OWner. I want to show all Cars sorted by their owner.

(I don't want to use the statement() method since in that case I would have to write the whole query myself)

(*) using http://typo3.org/api/typo3cms/class_t_y_p_o3_1_1_c_m_s_1_1_extbase_1_1_persistence_1_1_generic_1_1_query.html

Upvotes: 1

Views: 2490

Answers (3)

Jpsy
Jpsy

Reputation: 20862

@Michael and @rob-ot are right. There is one pitfall that took me many hours and that I'd like to mention here:

If your sort field in your related table contains underscores, you have to provide its name to setSortOrderings in lowerCamelCase:

// with database column name my_car_sorting you must define:
$query->matching($constraint)->setOrderings(
    array('owner.myCarSorting' => \TYPO3\CMS\Extbase\Persistence\QueryInterface::ORDER_ASCENDING)
)->execute();

Upvotes: 0

rob-ot
rob-ot

Reputation: 1264

When working with 6.2

->setOrderings(Array('model.yourfield' => \TYPO3\CMS\Extbase\Persistence\QueryInterface::ORDER_ASCENDING))

Upvotes: 1

Michael
Michael

Reputation: 2331

Yes, it is possible (don't care for the $constraint for the moment):

$query->matching($constraint)->setOrderings(
    array('owner.sorting' => Tx_Extbase_Persistence_QueryInterface::ORDER_ASCENDING)
)->execute();

Assuming the field in you Car model is named owner and you want to sort by sorting field of the Owner model/table.

Upvotes: 3

Related Questions