如何在目标模型Laravel中通过model_type获取关系



我有一个不同消息(短信、电话、常见消息等(的列表,我正试图通过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');
}

好吧,这比看起来更容易。我的问题在文件中有答案。此代码将为我提供必要的数据:

型号:

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

服务:

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

谢谢@Giles Bennett

相关内容

最新更新