Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
625 views
in Technique[技术] by (71.8m points)

orm - Cakephp 3 NOT IN query

I think this is a common pattern, but I can't find the elegant CakePHP way of doing it. The idea is to remove the values from a list which have already been chosen. To use an example from the Cake book:

table Students (id int, name varchar)
table Courses (id int, name varchar)
table CoursesMemberships (id int, student_id int, course_id int, days_attended int, grade varchar)

All I want to do is create a query which returns the courses that a given student has not yet signed up for, most probably to populate a select dropdown.

If I weren't using Cake, I'd do something like

select * from Courses where id not in 
    (select course_id from CoursesMemberships where student_id = $student_id)

Or maybe an equivalent NOT EXISTS clause, or outer join trickery, but you get the idea.

I'm stumped how to do this elegantly in Cake. It seems to me that this would be a common need, but I've researched for awhile, as well as tried some query ideas, to no avail.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If you want to use a subquery, simply pass a query object as the condition value, like

$subquery = $Courses->CoursesMemberships
    ->find()
    ->select(['CoursesMemberships.course_id'])
    ->where(['CoursesMemberships.student_id' => $student_id]);

$query = $Courses
    ->find()
    ->where([
        'Courses.id NOT IN' => $subquery
    ]);

As an alternative there's also Query::notMatching() (as of CakePHP 3.1), which can be used to select records whichs associated records do not match specific conditions:

$query = $Courses
    ->find()
    ->notMatching('CoursesMemberships', function (CakeORMQuery $query) use ($student_id) {
        return $query
            ->where(['CoursesMemberships.student_id' => $student_id]);
    });

See also


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...