Laravel 多态嵌套关系表现出无法解释的行为
Laravel polymorphic nested relations showing unexplainable behaviour
我正在使用多态关系来处理食谱和评论的报告。我在查询中包含多态对象没有问题,但是当我还希望包含所述多态对象的所有者(用户)时,问题就来了。
起初我尝试了以下操作:
尝试 1. 控制器功能:
public function getReports() {
return Report::orderBy('created_at', 'DESC')
->with('reportable', 'reportable.user')
->get();
}
这没有导致错误,这很好,但它也没有将用户包含在结果中。
查看数据:http://pastebin.com/DDfM3Ncj
尝试 2。将代码添加到多态 Report Model(可以在底部看到):
protected $appends = array('target');
public function getTargetAttribute() {
return $this->reportable->user;
}
这正确地导致 'target' 被添加到我的结果中,其中包含可报告对象的用户。然而,这个 也神秘地 将用户添加到我的可报告对象中,这是我最初想要的,但现在是一个问题,因为我们有用户目标。
查看数据: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');
}
}
我们最终得到了一个非常简单的解决方案,即始终使用所需模型返回用户:
protected $with = array('user');
这显然有一个缺点,即现在在查询任何提到的模型时总是有用户急切地加载。但我们认为这是一种可以接受的损失,因为我们只有一个不需要用户的查询。
我们使用缓存使缺点变得更加微不足道,以至于我们非常喜欢这个解决方案,而不是忽略 "bug" 让两个用户返回。
我正在使用多态关系来处理食谱和评论的报告。我在查询中包含多态对象没有问题,但是当我还希望包含所述多态对象的所有者(用户)时,问题就来了。
起初我尝试了以下操作:
尝试 1. 控制器功能:
public function getReports() {
return Report::orderBy('created_at', 'DESC')
->with('reportable', 'reportable.user')
->get();
}
这没有导致错误,这很好,但它也没有将用户包含在结果中。
查看数据:http://pastebin.com/DDfM3Ncj
尝试 2。将代码添加到多态 Report Model(可以在底部看到):
protected $appends = array('target');
public function getTargetAttribute() {
return $this->reportable->user;
}
这正确地导致 'target' 被添加到我的结果中,其中包含可报告对象的用户。然而,这个 也神秘地 将用户添加到我的可报告对象中,这是我最初想要的,但现在是一个问题,因为我们有用户目标。
查看数据: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');
}
}
我们最终得到了一个非常简单的解决方案,即始终使用所需模型返回用户:
protected $with = array('user');
这显然有一个缺点,即现在在查询任何提到的模型时总是有用户急切地加载。但我们认为这是一种可以接受的损失,因为我们只有一个不需要用户的查询。
我们使用缓存使缺点变得更加微不足道,以至于我们非常喜欢这个解决方案,而不是忽略 "bug" 让两个用户返回。