Solved thread

This post is marked as solved. If you think the information contained on this thread must be part of the official documentation, please contribute submitting a pull request to its repository.

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



10.6k
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.phalconphp.com/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.