sz ashik
sz ashik

Reputation: 911

Unable to left join table on Phalcon

I need to execute left joining for some data retrieving. But surprisingly it doesn't give any answer also when I tried to echo something after that it doesn't echo anything.

$exam = $this->modelsManager->createBuilder()
    ->from('qz_exams')
    ->leftJoin('qz_courses', 'qz_courses.id = qz_exams.course_id')
    ->getQuery()
    ->execute();

foreach ($exam as $item) {
    echo $item->name . '<br>';
}
echo 'BOOM';

This is what I tried to do. I have also included Phalcon\Mvc\Model\Manage into my public/index.php file with dispatcher. It also does't give any error also. What did I do wrong here?

Upvotes: 4

Views: 1633

Answers (1)

Nikolay Mihaylov
Nikolay Mihaylov

Reputation: 3876

Note that Phalcon Query Builder uses Model name with full namespace, not only table name (like PHQL does). Here is a full working example:

$items = $this->modelsManager->createBuilder()
    ->columns([
        // Fetching only desired columns (prefered way)
        'table1.column1',
        'table1.column2',
        'table2.column1',
        'table2.column2',
        // Or fetching whole objects
        'table1.*',
        'table2.*',    
    ])
    ->from(['table1' => 'YourNamespaces\Table1ModelName'])
    ->leftJoin('YourNamespaces\Table2ModelName', 'table1.id = table2.foreign_key', 'table2')
    ->where('table1.column = :column:', ['column' => $whereValue])
    ->getQuery()->execute();

Also I would recommend to debug the results with

print_r($exam->toArray());

Upvotes: 3

Related Questions