jeudi 30 août 2018

Laravel Eloquent Relationship foreign key with condition?

I'm building a forum with threads and comments. Both threads and comments can be reported. So I have 3 models: Thread, Comment and Report.

The report table should be used for both threads and comments for users to report spam and harassment. It has the following columns:

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

reported_type can either be 'thread' or 'comment' and the reported_id is the id of the corresponding thread.

Now I am struggling to form proper relationships with eloquent. Because within the 'thread' model I cannot just say

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

because it's not clear whether the id belongs to a comment or a thread.

What could be a solution to this? I would really like to use one report table only to keep it simple.

Thanks!



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire