简体   繁体   English

如何使用查询生成器查询数据透视表值?

[英]How can I query a pivot table value using Query Builder?

I have two models and a pivot table: 我有两个模型和一个数据透视表:

Teacher Class Teacher Class

The pivot table is class_teacher . 数据透视表是class_teacher I am running a dynamic query where I can receive an array of class IDs and I want to see which teachers are assigned to them. 我正在运行一个动态查询,我可以在其中收到一组类ID,我想看看哪些教师被分配给他们。

A class can have many teachers and a teacher can be in many classes. 一个班级可以有很多老师,老师可以在很多班级。

What is the best way of querying this with query builder? 使用查询生成器查询此问题的最佳方法是什么?

So far I have run code using a whereHas modifier to pull in the relationship and then used whereIn to see if the values are present. 到目前为止,我已经使用whereHas修饰符运行代码来拉入关系,然后使用whereIn来查看值是否存在。 Some code is below for example: 有些代码如下:

return $builder->whereHas('classes', function ($query) use ($value) {
            $query->whereIn('class_teacher.class_id', $value);
        });

This doesn't trigger errors but it doesn't return any results when some should show up. 这不会触发错误,但是当某些错误显示时它不会返回任何结果。

What am I doing wrong? 我究竟做错了什么?

Thanks 谢谢

You can define your relationships on the model, and then you won't need to use the query builder for this simple case. 您可以在模型上定义关系,然后在这个简单的情况下不需要使用查询构建器。

So for example in your Class model add this: 例如,在您的Class模型中添加以下内容:

public function teachers()
{
    return $this->belongsToMany(Teacher::class);
}

Then you can just call: 然后你可以打电话:

// $values should be an array of class ids
$classes = Class::whereIn('id', $values)->with('teachers')->get();

Iterating over each class will give you teachers collection assigned to that class. 对每个班级进行迭代将为您分配给该班级的教师收集。 Another thing is that Class is reserved word in PHP so I am not sure you can use it like that. 另一件事是Class是PHP中的保留字,所以我不确定你可以像这样使用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM