In a cakephp 3 app, how do I build a query that finds all from a Table that does NOT contain it's associated table?

StackOverflow https://stackoverflow.com//questions/25019422

  •  21-12-2019
  •  | 
  •  

Question

Is there a simple way to get the inverse of the contain method of the querybuilder?

I'm using belongsToMany associations with a join table to associate the two Models.

EmailsTable $this->belongsToMany('Issues');

IssuesTable $this->belongsToMany('Emails');

so I can't just do something like:

$unparsed_emails = $this->Emails->find('all')->where(['issue_id is null']);

It seems like the inverse of the following would provide Emails that do NOT have associated Issues yet:

$unparsed_emails = $this->Emails->find->contain(['Issues']);  //need inverse of this

I think I must be missing something from the cakephp 3 ORM/Querybuilder documentation, but I can't find it.

Was it helpful?

Solution

I'm not yet that much into the query builder, so I'm not sure whether there are simpler methods, but a left join should do it.

$this->Emails
    ->find('all')
    ->leftJoin('emails_issues', 'emails_issues.email_id = Emails.id')
    ->where('emails_issues.id IS NULL');

This should translate into a query like

SELECT
    Emails.id AS `Emails__id`, ...
FROM
    emails AS Emails
LEFT JOIN
    emails_issues emails_issues ON emails_issues.email_id = Emails.id
WHERE
    emails_issues.id IS NULL

which would select all emails that don't have any issues assigned.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top