tractorcow-farm / silverstripe-fluent

Multi-language translate module for Silverstripe, without having to manage separate site trees.
BSD 3-Clause "New" or "Revised" License
93 stars 111 forks source link

Incorrect sort by translated field in relation #650

Open t3hn0 opened 4 years ago

t3hn0 commented 4 years ago

Test with two classes Organisation and OrganisationType.

class Organisation extends DataObject
{

    private static $db = [
        'Title' => 'Varchar(255)',
        ...
    ];

    private static $has_one = [
        'Type' => OrganisationType::class,
        ...
    ];

    private static $summary_fields = [
        'Title', 'Type.Title'
    ];

}

class OrganisationType extends DataObject
{

    private static $db = [
        'Title' => 'Varchar(255)',
    ];

}

YAML config:

Innovatif\DataObjects\Organisation:
  extensions:
    - 'TractorCow\Fluent\Extension\FluentExtension'

Innovatif\DataObjects\OrganisationType:
  extensions:
    - 'TractorCow\Fluent\Extension\FluentExtension'

SQL after I try to sort summary field:

SELECT 
    DISTINCT "Organisation"."ClassName", 
    "Organisation"."LastEdited", 
    "Organisation"."Created", 
    CASE WHEN "Organisation_Localised_sl_SI"."ID" IS NOT NULL THEN "Organisation_Localised_sl_SI"."Title" ELSE "Organisation"."Title" END AS "Title",
    "Organisation"."TypeID",
    "Organisation"."ID", 
    CASE WHEN "Organisation"."ClassName" IS NOT NULL THEN "Organisation"."ClassName" ELSE 'Innovatif\\DataObjects\\Organisation' END AS "RecordClassName", 
    'sl_SI' AS "Locale", 
    CASE WHEN "Organisation_Localised_sl_SI"."ID" IS NOT NULL THEN 'sl_SI' ELSE NULL END AS "SourceLocale", "type_OrganisationType"."Title" AS "_SortColumn0"
FROM "Organisation" 
LEFT JOIN "OrganisationType" AS "type_OrganisationType" ON "type_OrganisationType"."ID" = "Organisation"."TypeID" 
LEFT JOIN "Organisation_Localised" AS "Organisation_Localised_sl_SI" ON "Organisation"."ID" = "Organisation_Localised_sl_SI"."RecordID" AND "Organisation_Localised_sl_SI"."Locale" = ?
ORDER BY "_SortColumn0" ASC
LIMIT 30

Tested in CMS on GridFieldSortableHeader with the same result if I try simple test on front-end:

$out= [];
$list = Organisation::get()->sort('Type.Title');
foreach ($list as $itm) {
    if( !isset($out[$itm->TypeID]) ) {
        $out[$itm->TypeID] = $itm->Type()->Title;
    }
}
print_r($out);

I get results:

Array
(
    [346] => Dr**
    [11]  => So**
    [353] => Kr**
    [347] => Iz**
    [9]   => Vl**
    [349] => Ja**
    [8]   => Ob**
    [5]   => Mi**
    [345] => No**
    [354] => Or**
    [368] => Po**
    [6]   => Pr**
    [350] => Iz**
    [12]  => Ag**
    [7]   => Up**
    [386] => Zu**
)

Tested with Fluent 4.5.0 and 5.0.0 beta3 and got the same result.

Fluent sorts records in base table and not in translation table as it should.

tractorcow commented 4 years ago

Yes, it looks like it's due to the fact we are sorting on a joined table, rather than the base table. Good spotting. :)