Laravel雄辩的关系外键与条件?

时间:2018-08-30 08:53:37

标签: laravel laravel-5 eloquent relationship relation

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

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

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

reported_type可以是“线程”或“注释”,并且reported_id是相应线程的ID。

现在,我正在努力与雄辩的人建立适当的关系。因为在“线程”模型中,我不能只说

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

因为不清楚该ID是属于注释还是线程。

对此有什么解决方案?我真的只想使用一个报表表来简化它。

谢谢!

2 个答案:

答案 0 :(得分:3)

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

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

与其他模型相同

答案 1 :(得分:1)

相关问题