【问题标题】:如何在目标模型 Laravel 中通过 model_type 获取关系
【发布时间】:2022-01-22 02:14:29
【问题描述】:

我有一个不同消息(短信、电话、普通消息等)的列表,我正在尝试通过model_typemodel_id 在通用表中连接此列表:

Schema::create('lead_messages', function (Blueprint $table) {
    $table->foreignId('lead_id')->nullable()->constrained('leads')->onDelete('cascade');
    $table->string('model_type');
    $table->unsignedBigInteger('model_id');
    $table->index(['model_id', 'model_type'], 'lead_messages_model_id_model_type_index');
    $table->primary(['lead_id', 'model_id', 'model_type'], 'lead_messages_lead_model_type_primary');
    $table->softDeletes();
    $table->timestamps();
});

然后我可以为用户获取提要。

现在我正在尝试按模型获取所有实体。 是否可以通过表格字段获取?
类似的东西(这当然是错误的代码):

public function data()
{
    return $this->hasOne('model_type', 'id', 'model_id');
}

【问题讨论】:

  • 假设您有一个 Message 模型,并且该模型需要与不同数量的其他模型之一(PhoneCall、SMS、WhatsApp 等)相关联,那么听起来您想要走多态关系路线。 laravel.com/docs/8.x/…

标签: laravel eloquent relationship


【解决方案1】:

好的,这比看起来容易。我的问题in documentation 有答案。此代码将为我提供必要的数据:

型号:

public function data()
{
    return $this->morphTo(__FUNCTION__, 'model_type', 'model_id');
}

服务:

$response = LeadMessage::whereLeadId($request->lead_id)
    ->with('data')
    ->paginate(30);

感谢@Giles Bennett

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-04
    • 2018-03-06
    • 1970-01-01
    • 1970-01-01
    • 2017-01-12
    相关资源
    最近更新 更多