0
votes

I'm trying to join two tables in a service, using the query() method of a Phalcon\Mvc\Model object. Here's my code:

$result = $this->templateModel->query()
                            ->columns('\Render\Model\Templates.* ')
                            ->leftJoin('\Render\Model\Branches.*', '\Render\Model\Templates.branchId = b.Branches.id', 'b')
                            ->where("branchId = :branchId:")
                            ->bind(['branchId' => $this->branchData['id']])
                            ->execute()
                            ->toArray();

However, when loading the page, I get the following error:

 Phalcon\Mvc\Model\Exception: Scanning error before '\Render\Model\Br...' when parsing: SELECT \Render\Model\Templates.* FROM [Render\Model\Templates] LEFT JOIN [\Render\Model\Branches.*] AS [b] ON \Render\Model\Templates.branchId = b.Branches.id WHERE branchId = :branchId: (187) in /home/vis/projects/stm/app/Service/BranchService.php on line 61

The syntax I used comes from this Stackoverflow entry (granted, it's not the newest post, but I'm still using Phalcon 2.0.13.

Researching the problem mostly returns results about forbidden semicolumns in the query (example1, example2), but that's not the issue in my case.

With the join line commented, the query works fine, so the problem must lie in it. Any help is appreaciated.

2
Change '\Render\Model\Branches.*' to '\Render\Model\Branches'. You need to define the table you want to join with. Not the columns you want to select from the joining table - Timothy
Thanks, that did the trick. I'm seriously absent-minded recently... - Veselin Bakov

2 Answers

0
votes
SELECT \Render\Model\Templates.* 
FROM [Render\Model\Templates] 
LEFT JOIN [\Render\Model\Branches.*] AS [b] ON \Render\Model\Templates.branchId = b.Branches.id 
WHERE branchId = :branchId:

I assume that you know SQL a bit. Even if it is PhQL, you probably see part of LEFT JOIN [\Render\Model\Branches.*], which looks quite suspicious. It is not possible to join table to column in this declaration. Joins happen between two tables always.

A simle fix of:

// -------------------------------v (removed ".*")
->leftJoin('\Render\Model\Branches', '\Render\Model\Templates.branchId = b.Branches.id', 'b')

should fix your problem, assuming you have properly declared \Render\Model\Branches model.

-1
votes

It should be \Render\Model\Branches Also you should use model relation alias so you can do something like:

$modelsManager->registerNamespaceAlias('M', 'Render\Model');

And then just use M:Branches etc