4

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?

sz ashik
  • 881
  • 7
  • 20

1 Answers1

3

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());
Nikolay Mihaylov
  • 3,868
  • 8
  • 27
  • 32
  • I have tried your way. I didn't declare any namespace for my models. So I just give only my model name [code](https://ideone.com/Tayf2a). Even that `echo 'boom'` doesn't print after that. – sz ashik Jun 05 '16 at 12:57
  • Looking at your code print_r($exam.toArray()); you made a silly mistake :) Should be $exam->toArray() – Nikolay Mihaylov Jun 05 '16 at 13:01
  • Well that I have fixed after I commented :) but still I couldn't get any echo's or print_r – sz ashik Jun 05 '16 at 13:12
  • In your code link there is an error "PHP Fatal error: Using $this when not in object context in /home/MAJV1R/prog.php on line 2" Are you making this query in static method or outside of class context? If so you can try using the DI in static way: $di = \Phalcon\DI::getDefault(); More info here: https://docs.phalconphp.com/en/latest/reference/di.html#accessing-the-di-in-a-static-way – Nikolay Mihaylov Jun 05 '16 at 13:34
  • Have you solved the problem? If so tell us what you did and mark question as answered. – Nikolay Mihaylov Jun 05 '16 at 14:11
  • 1
    `->leftJoin('Courses','qz_exams.course_id=qz_course.id','qz_courses')`.it should be `qz_courses.id` instead of `qz_course.id`. Thanks for your help. You saved me from lot of trouble. :) – sz ashik Jun 06 '16 at 16:30