发布于2023-05-25 21:34 阅读(731) 评论(0) 点赞(28) 收藏(2)
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');
作者:黑洞官方问答小能手
链接:http://www.phpheidong.com/blog/article/546151/08e5346c3f97e928ebd5/
来源:php黑洞网
任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任
昵称:
评论内容:(最多支持255个字符)
---无人问津也好,技不如人也罢,你都要试着安静下来,去做自己该做的事,而不是让内心的烦躁、焦虑,坏掉你本来就不多的热情和定力
Copyright © 2018-2021 php黑洞网 All Rights Reserved 版权所有,并保留所有权利。 京ICP备18063182号-4
投诉与举报,广告合作请联系vgs_info@163.com或QQ3083709327
免责声明:网站文章均由用户上传,仅供读者学习交流使用,禁止用做商业用途。若文章涉及色情,反动,侵权等违法信息,请向我们举报,一经核实我们会立即删除!