【问题标题】:Join and order polymorphic relationships in Laravel在 Laravel 中加入和排序多态关系
【发布时间】:2017-05-29 09:22:03
【问题描述】:

我有问题。比方说,我有一张桌子

personal_contacts[name, email, something_else]

和表

organisation_contacts[title, email, something, smth_else].

两个表都包含email 列。

另外,我还有一张桌子

needed_contacts[belonging_id, belonging_type],

与其他两个存在多态关系。

现在,我需要通过关系的 email 字段订购 needed_contacts。我打算通过连接而不是通过电子邮件字段订购来执行此操作,但如果我不重命名一个字段,则会收到错误消息:

Integrity constraint violation: Column 'email' in field list is ambiguous

是否有可能实现我想要做的事情?任何帮助、指针或 cmets 将不胜感激。

我的php代码是:

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');

【问题讨论】:

    标签: php mysql laravel-5 eloquent


    【解决方案1】:

    该查询将生成包含两个电子邮件列的结果,一个用于每个相关表。您可以像这样在 order 语句中选择表:

    ->orderBy('personal_contacts.email', 'desc');
    

    但我想这不是你真正想要的。您可以将计算列添加到将两个电子邮件列连接在一起的选择中,然后按此新列排序:

    ->selectRaw("CONCAT(COALESCE(personal_contacts.email, ''), COALESCE(organisation_contacts.email, '')) AS concat_email")
    ->orderBy('concat_email', 'desc');
    

    【讨论】:

      猜你喜欢
      • 2023-01-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-09-27
      • 1970-01-01
      • 1970-01-01
      • 2014-02-24
      • 1970-01-01
      相关资源
      最近更新 更多