Search code examples
phpsymfonydata-access-layershopware

Shopware6 - not able to get values due to my foreach loop


We currently have this code to get some property group options :

//Nederlands & English
$languages = ['94a1a2d118464bdaab37d6e05d404508', '2fbb5fe2e29a4d70aa5854ce7ce3e20b'];
$context = new Context(new SystemSource(), [], Defaults::CURRENCY, $languages);
$criteria = new Criteria();

Foreach ($propertiesArray as $property)
{
    $criteria->addFilter(new EqualsFilter('name', $property['name']);
    $lineInfo = $this->propertyGroupOptionRepository->search($criteria, $context)->first();
    var_dump($lineInfo);
}

For some reason, it's not able to get the value 'Zilver' and $lineInfo returns empty object. But the value 'Zilver' is Existing in the db with the language_id of 'Nederlands' = 94a1a2d118464bdaab37d6e05d404508 (Given in the context).

Strange fact : It is perfectly working for the first item of my $propertiesArray array. If I try to replace $property['value'] by 'Zilver' manually and isolate it from the foreach loop, I can get the result I need.

Am I doing something wrong or misunderstood the way it works?

Here is the dump of $propertiesArray =

      [0]=>
      array(1) {
        ["value"]=>
        string(10) "Eenkleurig"
      }
      [1]=>
      array(1) {
        ["value"]=>
        string(6) "Zilver"
      }
      [2]=>
      array(1) {
        ["value"]=>
        string(5) "Praag"
      }

Info : the main language of our instance is English but we are currently working with a system who sends us values in Nederlands.


Solution

  • I'm not completely sure about shopware but, your logic appears to be flawed as you are adding an additional EqualsFilter to the same Criteria in each iteration. That's why only the first search is successful.
    Try creating a new Criteria inside the loop.

    //Nederlands & English
    $languages = ['94a1a2d118464bdaab37d6e05d404508', '2fbb5fe2e29a4d70aa5854ce7ce3e20b'];
    $context = new Context(new SystemSource(), [], Defaults::CURRENCY, $languages);
    
    Foreach ($propertiesArray as $property)
    {
        $criteria = new Criteria();
        $criteria->addFilter(new EqualsFilter('name', $property['name']);
        $lineInfo = $this->propertyGroupOptionRepository->search($criteria, $context)->first();
        var_dump($lineInfo);
    }
    

    After looking through the docs, I think you may actually want to use the EqualsAnyFilter and then you should only need to make one query to the database. This should be much more efficient.

    //Nederlands & English
    $languages = ['94a1a2d118464bdaab37d6e05d404508', '2fbb5fe2e29a4d70aa5854ce7ce3e20b'];
    $context = new Context(new SystemSource(), [], Defaults::CURRENCY, $languages);
    $criteria = new Criteria();
    
    $criteria->addFilter(new EqualsAnyFilter('name', array_column($propertiesArray, 'name')));
    $results= $this->propertyGroupOptionRepository->search($criteria, $context);
    var_dump($results);