【问题标题】:How to alias polymorphic table in Laravel/Eloquent如何在 Laravel/Eloquent 中为多态表起别名
【发布时间】:2017-12-14 17:38:17
【问题描述】:

有以下型号和表格

CallRequest (parent)
    'id',
    'parent_id',
    'phone_number',
    'extension_id',
    'extension_type',

public $morphTo = [
    'extension' => [],
];


AsapLead (children)
    'id'

public $morphOne = [
    'call_request' => [
        CallRequest::class,
        'name' => 'extension',
    ],
];

其中包含多态关系。为了避免数据透视表,所有数据都存储在一张表中,因此父调用不会填充parent_idextension_idextension_type。只有孩子才会有这些。 Asap 领导只有id,其余所需信息在其父项中。

流程: 首先,它创建了parent 调用parent_id = null。如果调用失败,则创建子调用,通过parent_id 与前一个调用连接。另外,它添加了extension_type,因为它们不止一个扩展,但不是很复杂,我们在这种情况下只对一个进行操作。然后我需要检索 父调用,它有 最多 3 个子,并且创建时间不早于 7 天。查询如下所示:

$callRequestTable = CallRequest::table();
$leadTable = CallRequest::table() . " as lead";

DB::table($leadTable)
    ->rightjoin($callRequestTable, 'lead.id', '=', $callRequestTable . '.parent_id')
    ->where($callRequestTable . '.extension_type', '=', AsapLead::class)
    ->where($callRequestTable . '.created_at', '>', Carbon::now()->subDays(7))
    ->groupBy('lead.id')
    ->having(DB::raw('count(*)'), '<', 3)
    ->select('lead.*')
    ->get();

但不幸的是,它不起作用。最好在CallRequest::... 上进行操作,以便最终获得这些模型而不是普通数组,但我也无法弄清楚。

【问题讨论】:

    标签: php mysql laravel eloquent polymorphic-associations


    【解决方案1】:

    您必须在查询中使用Raw Expressions 将表名转换为 sql 表达式,这是一个示例:

    DB::table( DB::raw('callRequests AS leads') )->...
    

    【讨论】:

      【解决方案2】:

      这终于对我有用了:

      $callRequestTable = CallRequest::table();
      $leadTable = CallRequest::table() . " as lead";
      
      return CallRequest::from(DB::raw($leadTable))
          ->leftJoin($callRequestTable, 'lead.id', '=', $callRequestTable . '.parent_id')
          ->where('lead.extension_type', '=', AsapLead::class)
          ->where('lead.created_at', '>', Carbon::now()->subDays(7))
          ->groupBy('lead.id')
          ->having(DB::raw('count(*)'), '<', 3)
          ->select('lead.*');
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-01-13
        • 2013-07-16
        • 2017-10-07
        • 2016-05-24
        • 2021-10-19
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多