I have a problem. Let's say, I have a table of
personal_contacts[name, email, something_else]
and table of
organisation_contacts[title, email, something, smth_else]
.
Both tables contains email
column.
Besides, I have a table of
needed_contacts[belonging_id, belonging_type]
,
that is in polymorphic relation to other two.
Now, I need to order needed_contacts
by relationship's email
field. I was planning to do this with joins and than order by email field, but I get an error, if I don't rename one field:
Integrity constraint violation: Column 'email' in field list is ambiguous
Is it even possible to achieve, what I am trying to do? Any help, pointers or comments would be appreciated.
My php code is:
NeededContact::leftJoin('personal_contacts', function($join){
$join->on('personal_contacts.id', '=', 'needed_contacts.belonging_id')->where('needed_contacts.belonging_type', '=', 'PersonalContact');
})
->leftJoin('organisation_contacts', function($join){
$join->on('organisation_contacts.id', '=', 'needed_contacts.belonging_id')->where('needed_contacts.belonging_type', '=', 'OrganisationContact');
})
->orderBy('email', 'desc');
That query will produce results with two email columns, one for each related table. You can select the table in the order statement like this:
->orderBy('personal_contacts.email', 'desc');
But I guess this is not what you really want. You could add a computed column to the select that concatenates the two email columns in one and then order by this new column:
->selectRaw("CONCAT(COALESCE(personal_contacts.email, ''), COALESCE(organisation_contacts.email, '')) AS concat_email")
->orderBy('concat_email', 'desc');
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.