[英]Select from table 1 with foreign_key = x on table 2 where table 2 foreign key = Y on table 3
Not sure if the title makes much sense, but here is a better description: I have a table of shifts that have an id for the shift worker and an id for the client the shift worker does something for, and the clients table has a user id with associated record in users table.不确定标题是否有意义,但这里有一个更好的描述:我有一个轮班表,其中有一个轮班工人的 id 和一个轮班工人为之做某事的客户的 id,并且客户表有一个用户id 与用户表中的关联记录。
I would like to select all shifts that have a client id where the associated user id on the client record is X.我想 select 所有班次都有一个客户 ID,其中客户记录上的关联用户 ID 是 X。
Shifts Table
shift_id
shiftworker_id
client_id
...
Clients Table
client_id
user_id
...
Users Table
user_id
...
So, I want all the records (from shifts) where the client_id for the shift belongs to a specific user.所以,我想要所有记录(来自班次),其中班次的 client_id 属于特定用户。
User has many clients, and client has many shifts associated with it.用户有很多客户,客户有很多与之相关的班次。 I think what I am after is some kind of join like this:我想我追求的是这样的加入:
select * from shifts join shifts.client_id on clients.id and where clients.user_id = X
I am trying to do this in Laravel, like:我正在尝试在 Laravel 中执行此操作,例如:
DB::table('shifts')->join('clients', 'client_id', '=', ...)->join('users', 'client_id', '=', X);
Although any help with the SQL is appreciated and I can figure out the Laravel query from there.尽管对 SQL 的任何帮助表示赞赏,但我可以从那里找出 Laravel 查询。
Thank you谢谢
The easiest way will be to create a "has many through relationship" and query the User model with "user id" instead of querying shifts.最简单的方法是创建“具有多个直通关系”并使用“用户 ID”查询用户 model,而不是查询班次。
class User extends Model
{
public function shifts()
{
return $this->hasManyThrough(Shift::class, Client::class);
}
}
class ShiftController extends Controller
{
public function index()
{
return User::where('id', 1)->with('shifts')->first()->shifts;
}
}
If it works, the controller code will return the records from the shifts table without any relational data or extra fields.如果有效,controller 代码将返回班次表中的记录,不带任何关系数据或额外字段。 If you need to add some extra fields, this method might not be the best one.如果您需要添加一些额外的字段,此方法可能不是最好的方法。 In this case, give more details about the desired output data.在这种情况下,请提供有关所需 output 数据的更多详细信息。
UPDATE AFTER THE COMMENT评论后更新
You don't need to use any eloquent relation function to get shift data per client, because client_id is already on the shift tables.您不需要使用任何 eloquent 关系 function 来获取每个客户的班次数据,因为 client_id 已经在班次表上。 All you need is:所有你需要的是:
Shift::where('client_id', $client_id)->get();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.