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 在两列上有许多关系


基础教程推荐
- 如何在 XAMPP 上启用 mysqli? 2021-01-01
- 找不到类“AppHttpControllersDB",我也无法使用新模型 2022-01-01
- PHP 守护进程/worker 环境 2022-01-01
- 如何在 Symfony 和 Doctrine 中实现多对多和一对多? 2022-01-01
- phpmyadmin 错误“#1062 - 密钥 1 的重复条目‘1’" 2022-01-01
- 在 CakePHP 2.0 中使用 Html Helper 时未定义的变量 2021-01-01
- HTTP 与 FTP 上传 2021-01-01
- Doctrine 2 - 在多对多关系中记录更改 2022-01-01
- 使用 PDO 转义列名 2021-01-01
- 在 yii2 中迁移时出现异常“找不到驱动程序" 2022-01-01