Skip to content

[5.x]: Relation query using the field handle does not take the current site into account #18781

@MoritzLost

Description

@MoritzLost

What happened?

Description

I'm seeing an issue where an the query condition for an entries field does not take the current site into account.

Steps to reproduce

  1. Create two sites.
  2. Create a section categories, with entries set to manual propagation.
  3. Create a section projects, with entries set to manual propagation.
  4. Create an entries field category, limited to the categories section, with translation method set to Translate for each site.
  5. Create a couple of categories and one project and propagate them to both sites.
  6. In one project, select different categories in one site than in the other.
  7. In any template, use the following queries:
{% set category = craft.entries().id(12345).one() %}
{% set projectsQueryCategory = craft.entries()
    .section('projects')
    .category(currentCategory)
%}
{% set projectsQueryRelatedTo = craft.entries()
    .section('projects')
    .relatedTo(currentCategory)
%}

Where 12345 is the ID of a category that is selected in the project for one site, but not the other.

Expected behavior

Both queries should return the same result. When the template is executed in the site where category 12345 is related to the project entry, this entry should be returned by both queries. When the template is executed in the site where the category 12345 is not related to the project, no results should be returned.

Actual behavior

What I'm seeing is that only the query using relatedTo behaves correctly. Checking the raw SQL, it limits results to the current site:

`elements`.`id` IN (
    SELECT `sources1`.`targetId`
    FROM `relations` `sources1`
    WHERE (`sources1`.`sourceId` = 12345)
        AND (
            (`sources1`.`sourceSiteId` IS NULL)
            OR (`sources1`.`sourceSiteId` = 2)
        )
)

The query using the field handle .category(12345) does not limit the results by sourceSiteId, which means the relations from the other site are found as well:

`elements`.`id` IN (
    SELECT `targets1`.`sourceId`
    FROM `relations` `targets1`
    WHERE (`targets1`.`targetId` = 12345)
        AND (`targets1`.`fieldId` = 128)
)

Craft CMS version

5.9.17

PHP version

No response

Operating system and version

No response

Database type and version

No response

Image driver and version

No response

Installed plugins and versions

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions