【问题标题】:Laravel Eloquent Relationship foreign key with condition?Laravel雄辩的关系外键与条件?
【发布时间】:2018-08-30 08:53:37
【问题描述】:

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

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

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

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

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

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

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

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

谢谢!

【问题讨论】:

标签: laravel laravel-5 eloquent relationship relation


【解决方案1】:

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

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

同样转到另一个模型

【讨论】:

  • 哇,这就是我猜到的。Laravel 太简单了。但是我没有在文档中找到它。谢谢老哥!
【解决方案2】:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-29
    • 2017-05-19
    • 1970-01-01
    • 1970-01-01
    • 2021-12-18
    • 1970-01-01
    相关资源
    最近更新 更多