2

I have a Product entry type that contains a field for Components (which are also products) and a field for Related Products (again, also Products). I want to be able to find a parent product from a Component, but using a relatedTo() gives me all the Products on which it is a Related Product as well.

Is there a way to specify which field you want to use with the relatedTo() method?

$product = Entry::find()->section('products')->relatedTo($component)->one();

Expected result = The parent product.

Actual result = A random product on which the component is a related item.

Of course, this was all working great until I just recently added the Related Products field.

2

Haha. I figured it out. Leaving the answer here in case anyone else runs into the same problem:

$product = Entry::find()->section('products')->relatedTo([
    'element' => $component,
    'field' => 'productComponents'
])->one();

You can pass an object/array to the relatedTo() method as described here:

Relations | Craft 3 Documentation

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.