Ich habe drei Tabellen customers
, organizations
und contacts
. Tabelle customers
Tabelle hat Spalten customer_class
(die Klasse zeigt Tabelle Verwendung Organization
, Contact
) und customer_id
(entspricht Spalte id
in entweder organizations
oder contacts
).Laravel Bedingt Join Tabellen basierend auf angegebenen Klasse
Also, was ich tat, war
$interactions = DB::table('sales_interactions')
->join('customers', 'customers.id', '=', 'sales_interactions.customer_id')
->join('organizations', function($join)
{
$join->on('customers.customer_id', '=', 'organizations.id')
->where('customers.customer_class', '=', 'Organization');
})
->join('contacts', function($join)
{
$join->on('customers.customer_id', '=', 'contacts.id')
->where('customers.customer_class', '=', 'Contact');
})
->select([
'organizations.title as customer',
'contacts.name as customer',
'sales_interactions.id',
'sales_interactions.created_at',
'sales_interactions.title',
'status',
'deadline',
'value',
]);
Es funktionierte, als ich nur Organisationen beigetreten. Das Verknüpfen von Kontakten gibt jedoch null Ergebnisse zurück.
Ok Ich habe meinen Eintrag mit einer Union, die Sie brauchen, reedit ... –
Ja, mein Problem ist, dass ich immer auf der Suche nach komplexen Möglichkeiten, Sachen zu tun :) Ich habe versucht, etwas wie 'JOIN ((SELECT organizations.title AS Kunde von Organisationen, in denen customers.customer_class = 'Organization') UNION (SELECT contacts.name AS Kunde von Kunden, bei denen customers.customer_class = 'Contact')) ', aber Ihr sollte gut funktionieren und das ist alles Angelegenheiten. Vielen Dank!!! –
Followup - Ich füttere eine kombinierte Abfrage in 'Datatables :: of ($ interactions) ...', wenn es versucht, alle Spalten abzufragen ich bekomme Fehler '1054 Unbekannte Spalte 'Kunde' in 'where clause'' –