我使用多态关系来处理食谱和评论的报告。我在查询中包含多态对象没有问题,但是当我希望还包括所述多态对象的所有者(用户)时,问题就出现了。
起初我尝试了以下内容:
尝试1。控制器功能:
public function getReports() {
return Report::orderBy('created_at', 'DESC')
->with('reportable', 'reportable.user')
->get();
}
这导致没有错误,这很好,但 没有 在结果中包含用户。
参见数据:http://pastebin.com/DDfM3Ncj
尝试2 。为多态 报表模型 添加了代码(可在底部看到):
protected $appends = array('target');
public function getTargetAttribute() {
return $this->reportable->user;
}
这正确地导致了一个'目标'被添加到我的结果中,持有可报告对象的用户。然而, ALSO Mysteriously 将用户添加到我的可报告对象中,这是我最初想要的,但现在出现问题,因为我们将用户置于目标之下。
参见数据:http://pastebin.com/4DD8imbN
如何让用户获得多态关系而不会突然结束两个。
注意: (以下代码 可能 不需要回答)
public function getReports(t) {
return Report::orderBy('created_at', 'DESC')
->with('reportable')
->get();
}
多态模型
class Report extends Model {
public function reportable() {
return $this->morphTo();
}
public function User() {
return $this->belongsTo('App\User');
}
}
食谱模型
class Recipe extends Model {
public function user() {
return $this->belongsTo('App\User');
}
public function reports() {
return $this->morphMany('App\Report', 'reportable');
}
}
评论模型
class RecipeComment extends Model {
public function user() {
return $this->belongsTo('App\User');
}
public function reports() {
return $this->morphMany('App\Report', 'reportable');
}
}
答案 0 :(得分:5)
我们最终得到了一个非常简单的解决方案,即始终使用以下方法返回具有所需模型的用户:
protected $with = array('user');
这显然有一个缺点,即在查询任何提到的模型时,现在总是有用户急切加载。但我们认为这是一种可接受的损失,因为我们只有一个查询,其中不需要用户。
我们使用缓存使缺点变得更加微不足道,以至于我们非常希望这个解决方案能够忽略" bug"让两个用户返回。