Skip to content

Querying

Michael O'Connell edited this page Sep 13, 2024 · 9 revisions

Corma supports a simple array-based query syntax everywhere that a where query is accepted. The array keys define the column, while the value specifies the value to query for. The column can optionally declare a comparison operator (=, <, >, <=, >=, <>, !=, LIKE, NOT LIKE, BETWEEN, NOT BETWEEN). If an array is specified for the value it translates to an IN() (or NOT IN() if <> or != is used) clause.

$objects = $orm->findBy(MyObject::class, ['columnA'=>'A', 'columnB >'=> 10, 'columnC' => null, 'inColumn'=>[1,2,3], 'betweenColumn BETWEEN'=>[2, 10]]);

Would translate to roughly the following SQL:

SELECT * FROM my_objects main WHERE columnA = 'A' AND columnB > 10 AND columnC IS NULL AND inColumn IN(1,2,3) AND betweenColumn BETWEEN 2 AND 10

While this handles the most common use cases, you will need to work with the Doctrine QueryBuilder directly for the following scenarios:

  1. Joins
  2. You need an OR in your where clause
  3. Group by statements
  4. Having statements

In that case you can use the Corma QueryHelper to start your query, and then manipulate the QueryBuilder in your repository methods.

Because your relationships define what foreign columns / join tables exist, it can join any relationship by specifying the relationship name.

class MyObject {

    #[OneToMany(OtherObject::class)]
    private array $propertyWithRelationships;

    public function setPropertyWithRelationships(array $otherObjects): void {
        $this->propertyWithRelationships = $otherObjects;
    }
    
    public function getPropertyWithRelationships(): array {
        return $this->propertyWithRelationships
    }
}


And join to the other_objects table in your repository.

/**
* Repository method
* @return MyObject[]
*/
public function findWithJoin(string $value): array
{
    $qb = $this->queryHelper->buildSelectQuery($this->getTableName(), 'main.*', ['pwr.columnName'=>$value, 'rooc.columnName'=>'otherValue'])
    $alias = $this->join($qb, 'propertyWithRelationships') //alias is first letter of each word in a camel case property name
    //Then do a left join to another property from the foreign table
    $this->join($qb, 'relationshipOnOtherClass', OtherClass::class, $alias, type: JoinType::LEFT)
    $qb->groupBy('main.id');
    return $this->fetchAll($qb);
}