Laravel 5 在两列上有许多关系

Laravel 5 hasMany relationship on two columns(Laravel 5 在两列上有许多关系)
本文介绍了Laravel 5 在两列上有许多关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在两列上建立 hasMany 关系?

Is it possible to have a hasMany relationship on two columns?

我的表有两列,user_idrelated_user_id.

My table has two columns, user_id and related_user_id.

我希望我的关系匹配任一列.

I want my relation to match either of the columns.

在我的模型中我有

public function userRelations()
{
    return $this->hasMany('AppUserRelation');
}

运行查询:select * from user_relations where user_relations.user_id in ('17', '18').

我需要运行的查询是:

select * from user_relations where user_relations.user_id = 17 OR user_relations.related_user_id = 17 

我正在使用预先加载,我认为这会影响它的工作方式.

I'm using eager loading and I think this will affect how it will have to work.

$cause = Cause::with('donations.user.userRelations')->where('active', '=', 1)->first();

推荐答案

我认为不可能完全按照您的要求去做.

I don't think it's possible to do exactly what you are asking.

我认为您应该将它们视为单独的关系,然后在模型上创建一个新方法来检索两者的集合.

I think you should treat them as separate relationships and then create a new method on the model to retrieve a collection of both.

public function userRelations() {
    return $this->hasMany('AppUserRelation');
}

public function relatedUserRelations() {
    return $this->hasMany('AppUserRelation', 'related_user_id');
}

public function allUserRelations() {
    return $this->userRelations->merge($this->relatedUserRelations);
}

通过这种方式,您仍然可以在模型上获得预先加载和关系缓存的好处.

This way you still get the benefit of eager loading and relationship caching on the model.

$cause = Cause::with('donations.user.userRelations', 
        'donations.user.relatedUserRelations')
    ->where('active', 1)->first();

$userRelations = $cause->donations[0]->user->allUserRelations();

这篇关于Laravel 5 在两列上有许多关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Convert JSON integers and floats to strings(将JSON整数和浮点数转换为字符串)
in php how do I use preg replace to turn a url into a tinyurl(在php中,如何使用preg替换将URL转换为TinyURL)
all day appointment for ics calendar file wont work(ICS日历文件的全天约会不起作用)
trim function is giving unexpected values php(Trim函数提供了意外的值php)
Basic PDO connection to MySQL(到MySQL的基本PDO连接)
PHP number_format returns 1.00(Php number_Format返回1.00)