CREATE VIEW IF NOT EXISTS template_widgets AS
SELECT id
FROM (
         SELECT dw.id,
                COALESCE(q.company_id, i.company_id, c.company_id) AS widgetable_company_id,
                COALESCE(q.flow_id, i.flow_id, c.flow_id)          AS widgetable_flow_id

         FROM document_widgets dw
                  LEFT JOIN quotations q ON (
                 dw.widgetable_type = 'App\\Quotation' AND
                 dw.widgetable_id = q.id
             )
                  LEFT JOIN invoices i ON (
                 dw.widgetable_type = 'App\\Invoice' AND
                 dw.widgetable_id = q.id
             )
                  LEFT JOIN confirmations c ON (
                 dw.widgetable_type = 'App\\Confirmation' AND
                 dw.widgetable_id = c.id
             )
     ) widgets_with_relations
WHERE COALESCE(widgetable_company_id, 0) != 0
  AND COALESCE(widgetable_flow_id, 0) = 0
