We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

Model::find() which has related Model more than 0

Hello.

I want to return all objects which has at least one related object, before I paginate it. I know that I can create my "find" method, but I'm pretty sure there is functionality like this already in Phalcon.

I've got 2 models:

  • Companies (hasMany Workers)
  • Workers (belongsTo Companies)

And got this code:

$companies_before = Companies::find( [ 'order' => 'slug ASC' ] );

I would like to make it like this:

$companies_before = Companies::find( [ 'order' => 'slug ASC' 'conditions' => Company->Workers->count() is more than 0 ] );

Is there "one-line" solution already in Phalcon?

Regards



12.8k
Accepted
answer
$companies_before = Companies::find( [
    'conditions'=>'exists(select 1 from Workers where Worker.company_id = Companies.id)',
    'order' => 'slug ASC' 
] );

You need to replace Worker.company_id and Companies.id by unique mapped columns name
https://olddocs.phalcon.io/en/3.0.0/reference/models-advanced.html#independent-column-mapping

Java. Java decreased in popularity by about 6,000 job postings in 2018 compared to 2017, but is still extremely well-established. ... Python. Python grew in popularity by about 5,000 job postings over 2017. ... JavaScript. ... C++ ... C# ... PHP. ... Perl.