[英]multiple “has many through” with eloquent of laravel
I came accros a problem with laravel's ORM, eloquent and found no solution yet. 我雄辩地说,laravel的ORM出了问题,但没有找到解决方案。
I have some tables as follows 我有一些表格如下
Team 球队
- id
- name
User 用户
- id
- name
- role
- team_id
Student_Info 学生信息
- id
- user_id
- data1
- data2
- etc ...
Project 项目
- id
- student_id
- name
Now, I want to query all projects a certain team
, where team = 'some team'
现在,我要查询某个team
所有项目,其中team = 'some team'
Now the thing here is, without an ORM, it's simple, I would have done multiple joins in raw SQL. 现在,这里的事情是,没有ORM,这很简单,我将在原始SQL中进行多个联接。
However, because all these tables have a common column "name" I will have to alias all this stuff, which is really boring 但是,由于所有这些表都有一个公共列“名称”,因此我必须为所有这些东西加上别名,这确实很无聊
With eloquent I can't find a way to do this query using "has many through" because it only allows on intermediate and I can't do a raw SQL as the alis thing is really a pain in the ass and as it would be very difficult to map the result to laravel's Models 雄辩地说,我找不到使用“有很多通过”的方式进行此查询的方法,因为它只允许使用中级语言,而我无法执行原始SQL,因为alis的事情确实很麻烦,因为它将结果映射到laravel的模型非常困难
Try with relationship existence. 尝试建立关系。 This assumes you have all relationships properly defined 假设您已经正确定义了所有关系
$projects = Project::whereHas('students.user.team', function ($query) {
$query->where('name', '=', 'some team');
})->get();
That's 3 levels of nesting. 这是3个层次的嵌套。 Never tested. 从未测试。 However, if you already define a Project-User relationship via hasManyThrough()
you can shorten it to 2 levels only. 但是,如果您已经通过hasManyThrough()
定义了项目-用户关系, hasManyThrough()
只能将其缩短到2级。
$projects = Project::whereHas('user.team', function ($query) {
$query->where('name', '=', 'some team');
})->get();
Those will give you the data for projects only. 这些将仅为您提供项目数据。 If you also want the the intermediate data, use eager loading instead with with()
. 如果您还需要中间数据,请使用即时加载代替with()
。 Just replace whereHas()
by with()
. 只需用whereHas()
替换whereHas()
with()
。
$projects = Project::with('user.team', function ($query) {
$query->where('name', '=', 'some team');
})->get();
There is no native relationship for this case. 在这种情况下没有本机关系。
I created a HasManyThrough
relationship with unlimited levels: Repository on GitHub 我创建了一个具有无限级别的HasManyThrough
关系: GitHub上的存储库
After the installation, you can use it like this: 安装后,您可以像这样使用它:
class Team extends Model {
use \Staudenmeir\EloquentHasManyDeep\HasRelationships;
public function projects() {
return $this->hasManyDeep(Project::class, [User::class, StudentInfo::class],
[null, null, 'student_id']);
}
}
$projects = Team::where('name', 'some team')->first()->projects;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.