Search code examples
phpmysqlsymfonydoctrine-ormshopware

Query Builder custom on clause


I want to map the following SQL statement with doctrine

select 
    address.*,
    (CASE WHEN (customer.default_billing_address_id = address.id) THEN 1 ELSE 0 END) as isDefaultBillingAddress,
    (CASE WHEN (customer.default_shipping_address_id = address.id) THEN 1 ELSE 0 END) as isDefaultShippingAddress
from 
    s_user customer
join
    s_user_attributes customerattributes on customerattributes.customer_number = customer.customernumber
join
    s_user_addresses address on address.user_id = customer.id
where customerattributes.userID = 214

But when I write my doctrine query with the query builder I always get the query a little different:

[...]
FROM s_user_addresses s1_
[...]
INNER JOIN s_user_attributes s5_ ON s0_.id = s5_.userID
INNER JOIN s_user s0_ ON s0_.id = s5_.userID
AND (s5_.customer_number = s0_.customernumber)
WHERE s5_.userID = 214
ORDER BY sclr_0 DESC
  ,sclr_1 DESC

And finally this is the code that uses the query builder:

$builder->from(Address::class, 'address')
    ->andWhere('customerAttribute.customerId = :userId')
    ->setParameter('userId', $userId)
    ->join('address.customer', 'customer')
    ->join('customer.attribute', 'customerAttribute', Join::WITH, 'customerAttribute.customerNumber = customer.number')
    ->addSelect([
        '(CASE WHEN (customer.defaultBillingAddress = address.id) THEN 1 ELSE 0 END) as HIDDEN isDefaultBillingAddress',
        '(CASE WHEN (customer.defaultShippingAddress = address.id) THEN 1 ELSE 0 END) as HIDDEN isDefaultShippingAddress',
    ])
    ->addOrderBy('isDefaultBillingAddress', 'DESC')
    ->addOrderBy('isDefaultShippingAddress', 'DESC');

The problem is, that the JOIN clause gets an AND, I just want that the customer_number gets joined not the id's


Solution

  • Both conditions are added as you join by relation - this adds default condition by which relation is mapped.

    Just change 'customer.attribute' with full name of the entity, I guess something like CustomerAttribute::class.