[英]Access nested related objects with where clause in Laravel using Eloquent
I'm trying to get a list of tasks that are associated with a specific client, but there is no direct relation between a task and a client.我正在尝试获取与特定客户端关联的任务列表,但任务和客户端之间没有直接关系。 I also need to filter those tasks based on task status and project status.
我还需要根据任务状态和项目状态过滤这些任务。
Here are my models:这是我的模型:
class Client extends Model
{
// Fields ['id']
public function projects()
{
return $this->hasMany('App\Project');
}
}
class Project extends Model
{
// Fields ['id', 'client_id', 'status']
public function client()
{
return $this->belongsTo('App\Client');
}
public function tasks()
{
return $this->hasMany('App\Task');
}
}
class Task extends Model
{
// Fields ['id', 'project_id', 'status']
public function project()
{
return $this->belongsTo('App\Project');
}
}
In my controller, I have direct access to Client $client
from the request.在我的控制器中,我可以从请求中直接访问
Client $client
。
The goal is to return a list of tasks which have a status of 'open' and which are children of projects owned by the client.目标是返回状态为“打开”并且是客户拥有的项目的子项的任务列表。
Basically, I want to write something like this:基本上,我想写这样的东西:
$client->projects->where('status', 'active')->tasks->where('status', 'open');
And I want to get back what I'd get from this query:我想取回我从这个查询中得到的信息:
SELECT * FROM tasks AS t
WHERE t.status='open'
AND t.project_id IN (
SELECT id FROM projects AS p
WHERE p.status='active'
AND p.client_id=1
);
I've been able to solve it using Laravel's Query Builder, but I want a solution that uses Eloquent's ORM directly.我已经能够使用 Laravel 的 Query Builder 解决它,但我想要一个直接使用 Eloquent 的 ORM 的解决方案。
DB::table('tasks')
->join('projects', function($join) use ($client) {
$join->on('projects.id', '=', 'tasks.project_id')
->where('projects.client_id', '=', $client->id);
})->select('tasks.*')->get();
This seems to be a variation on a common question, but I've been unable to solve it with the other answers posted here.这似乎是一个常见问题的变体,但我一直无法使用此处发布的其他答案来解决它。
Related questions:相关问题:
laravel orm : where condition on table -> related table -> related table laravel orm:表上的条件 -> 相关表 -> 相关表
What you are looking for is whereHas
.您正在寻找的是
whereHas
。 It lets you query "results based on the existence of a relationship".它允许您查询“基于关系存在的结果”。
You could try something like:你可以尝试这样的事情:
Task::where('status', 'open')
->whereHas('project', function ($query) use ($client) {
$query->where('client_id', $client->id)
->where('status', 'active');
})
->get();
hasManyThrough
also applies on this structure: hasManyThrough
也适用于这个结构:
// In Client.php
public function tasks()
{
return $this->hasManyThrough(Task::class, Project::class);
}
$client->tasks()
->where('projects.status', 'active')
->where('tasks.status', 'open')
->get();
However not entirely sure if this would work.但是不完全确定这是否有效。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.