程序员最近都爱上了这个网站  程序员们快来瞅瞅吧!  it98k网:it98k.com

本站消息

站长简介/公众号

  出租广告位,需要合作请联系站长

+关注
已关注

分类  

暂无分类

标签  

暂无标签

日期归档  

暂无数据

Join and order polymorphic relationships in Laravel

发布于2023-05-25 21:34     阅读(707)     评论(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黑洞网

任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任

28 0
收藏该文
已收藏

评论内容:(最多支持255个字符)