Search code examples
phpclassobjectormidiorm

PHP split class function calls


I use PHP and Idiorm for SQL queries.

A normal query

This one works.

$females = ORM::for_table('person')
               ->where('gender', 'female')
               ->find_many();

Problem

In some cases I need to add another where-clause, without rewriting the whole query again. The result might look like this. It works.

$females = ORM::for_table('person')
               ->where('gender', 'female')
               ->where('parent', 22)
               ->find_many();

My try that failed

It somehow loses the object.

$females = ORM::for_table('person')
               ->where('gender', 'female');

if( ! empty( $parent ) )
{
$females->where('parent', $parent);
}

$females->find_many();

Solution

  • I don't know about Idiorm in particular, but you should be able to refactor that code to:

    $query = ORM::for_table('person')->where('gender', 'female');
    
    if ($parent) {
        $query->where('parent', $parent);
    }
    
    $females = $query->find_many();