Laravel 5 hasMany relationship on two columns(Laravel 5 在两列上有许多关系)
问题描述
是否可以在两列上建立 hasMany 关系?
Is it possible to have a hasMany relationship on two columns?
我的表有两列,user_id
和 related_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 在两列上有许多关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Laravel 5 在两列上有许多关系
- PHP foreach() 与数组中的数组? 2022-01-01
- 使用 GD 和 libjpeg 支持编译 PHP 2022-01-01
- Oracle 即时客户端 DYLD_LIBRARY_PATH 错误 2022-01-01
- 如何从数据库中获取数据以在 laravel 中查看页面? 2022-01-01
- 如何在 Symfony2 中正确使用 webSockets 2021-01-01
- PHP - if 语句中的倒序 2021-01-01
- 覆盖 Magento 社区模块控制器的问题 2022-01-01
- 如何使用 Google API 在团队云端硬盘中创建文件夹? 2022-01-01
- Laravel 5:Model.php 中的 MassAssignmentException 2021-01-01
- openssl_digest vs hash vs hash_hmac?盐与盐的区别HMAC? 2022-01-01