Laravel Eloquent关系外键与条件?

问题描述 投票:1回答:2

我正在建立一个包含线程和评论的论坛。可以报​​告线程和注释。所以我有3个模型:线程,评论和报告。

报告表应用于线程和评论,以便用户报告垃圾邮件和骚扰。它包含以下列:

$table->increments('id');
$table->string('reported_type');
$table->unsignedInteger('reported_id');

reported_type可以是'thread'或'comment',reported_id是相应线程的id。

现在我正在努力与雄辩的人形成适当的关系。因为在'线程'模型中我不能只说

public function reports()
{
    return $this->hasMany(Report::class, 'reported_id');
}

因为不清楚id是属于评论还是线程。

什么可以解决这个问题?我真的只想使用一个报表来保持简单。

谢谢!

laravel laravel-5 eloquent relationship relation
2个回答
3
投票

您可以在雄辩的关系中添加其他条件,例如:

public function reports()
{
    return $this->hasMany(Report::class, 'reported_id')->where('reported_type', 'thread');
}

同样去另一个模特


1
投票
© www.soinside.com 2019 - 2024. All rights reserved.