I got a rather simple application where a user can report other users comments and recipes. I use a polymorphic relation to store the reports. This all works fine, however I am now trying to get the offenses that a user has made.
Getting his own reports is not a problem, this can be done simply using user->reports() but I would very much like to get the reports in which other people has reported said user. I can get this to work using either the hasManyThrough relation or queries BUT only on one model at a time.
ex.
public function offenses() {
return $this->hasManyThrough('Recipe', 'Reports');
}
Or
->with('user.recipe.reports')
The problem is that my reportable object is not just recipes, it could be comments, images etc. So instead of having to use multiple functions, the logical way would be to somehow parse the relationship of hasManyThrough multiple parameters.
Theoretically looking like this:
public function offenses() {
return $this->hasManyThrough(['Recipe', 'RecipeComments'], 'Reports');
}
Is this in any way possible? With some undocumented syntax? If not is there any clever work-arounds/hacks?
Possible solution?
Would an acceptable solution be to add another column on my report table and simply add offender_id like this?
ID | User_id | Offender_id | Reportable_type | Reportable_id
This would mean I could simply make a relation on my user model that connects offenses through that column. But would this be considered redundant? Since I already have the offender through the reportable model?
Models
Polymorphic Model
class Report extends Model {
public function reportable() {
return $this->morphTo();
}
public function User() {
return $this->belongsTo('App\User');
}
}
Recipe Model
class Recipe extends Model {
public function user() {
return $this->belongsTo('App\User');
}
public function reports() {
return $this->morphMany('App\Report', 'reportable');
}
}
Comment Model
class RecipeComment extends Model {
public function user() {
return $this->belongsTo('App\User');
}
public function reports() {
return $this->morphMany('App\Report', 'reportable');
}
}
Aucun commentaire:
Enregistrer un commentaire