php – 使用Laravel Eloquents HasManyThrough通过多态关系与多个关系

php – 使用Laravel Eloquents HasManyThrough通过多态关系与多个关系,第1张

概述我有一个相当简单的应用程序,用户可以报告其他用户的评论和食谱.我使用多态关系来存储报告.哪个工作正常;但是,我现在正试图让用户犯下的罪行. 获取用户报告不是问题,可以使用user-> reports()直接完成,但我非常希望获得其他人报告该用户的报告.我可以使用hasManyThrough关系或者一次仅在一个模型上进行查询. 恩. public function offenses() { 我有一个相当简单的应用程序,用户可以报告其他用户的评论和食谱.我使用多态关系来存储报告.哪个工作正常;但是,我现在正试图让用户犯下的罪行.

获取用户报告不是问题,可以使用user-> reports()直接完成,但我非常希望获得其他人报告该用户的报告.我可以使用hasManyThrough关系或者一次仅在一个模型上进行查询.

恩.

public function offenses() {    return $this->hasManyThrough('Recipe','Reports');}

要么

->with('user.recipe.reports')

问题是我的可报告对象不仅仅是食谱,它可能是注释,图像等.因此,不必使用多个函数,逻辑方法是以某种方式解析hasManyThrough各种参数之间的关系.

理论上看起来像这样:

public function offenses() {    return $this->hasManyThrough(['Recipe','RecipeComments'],'Reports');}

这有可能吗?有一些没有文档的语法?如果不是,有任何聪明的解决方法/黑客?

可能的方案?

可接受的解决方案是在我的报告表上添加另一列并且只添加这样的offender_ID吗?

ID | User_ID | Offender_ID | Reportable_type | Reportable_ID

这意味着我可以在我的用户模型上建立关系,通过该列连接攻击.但这会被视为多余吗?由于我已经通过可报告模型获得了罪犯?

楷模

多态模型

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');    }}
使用当前模型,您可以通过以下代码接收用户的所有报告模型:
$recipeCommentReport = RecipeComment::whereHas('reports',function($q){   return $q->where('user_ID','=',Auth::user()->ID) });$recipeReport = Recipe::whereHas('reports',Auth::user()->ID) });//Get all reports into one$reports = $recipeReport->merge([$recipeCommentReport]);

这充其量是凌乱的,因为:

>鉴于我们使用两个单独的数据库查询,我们无法对结果进行排序.
>如果你有其他模特有报告关系,那就想象一下混乱.

最好的解决方案,就像你上面已经想到的那样:

将offender_ID列添加到报表中.

它更清洁,遵循DRY原则.

典型案例场景

获取用户的所有食谱评论报告

Report::where('offender_ID',Auth::check()->ID)->where('reportable_type','RecipeComment')->get();

按类型计算用户的攻击

Report::where('offender_ID',Auth::check()->ID)->grouBy('reportable_type')->select(Db::raw('count(*)'),'reportable_type')->get();
总结

以上是内存溢出为你收集整理的php – 使用Laravel Eloquents HasManyThrough通过多态关系与多个关系全部内容,希望文章能够帮你解决php – 使用Laravel Eloquents HasManyThrough通过多态关系与多个关系所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://www.outofmemory.cn/langs/1258970.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-07
下一篇 2022-06-07

发表评论

登录后才能评论

评论列表(0条)

保存