如何在Laravel / Eloquent中别名多态表

叔叔

有以下型号和表

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_id并且没有extension_type填充。只有孩子会吃那些。尽快导致id,其余所需信息在其父级中。

流程:首先,它使用创建了parentCall 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::...为了最终获得那些模型而不是简单的数组,进行操作甚至会更好,但是我还无法弄清楚。

叔叔

这终于对我有用:

$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.*');

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章