简体   繁体   中英

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

I have two models and a pivot table:

Teacher Class

The pivot table is 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.

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. 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:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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