We are moving our forum in GitHub Discussions. For questions about Phalcon v3/v4 you can visit here and for Phalcon v5 here.

Models Manager... how to BIND in ORDER BY?

Need to somehow recreate this query in Phalcon, been stuck on it for hours:

select      aud.*
from        address_user_detail aud
inner join  user u on u.id = aud.user_id
left join   property_address pa on pa.id = aud.address_id
where       u.account_id = 11
        and (
                match(aud.label, aud.notes) against ('SOME STRING') 
                or match(pa.street, pa.city, pa.state, pa.zip) against ('SOME STRING')
order by    match(aud.label, aud.notes) against ('SOME STRING') + match(pa.street, pa.city, pa.state, pa.zip) against ('SOME STRING')

I can't see how I can BIND 'SOME STRING' into the order by clause. Another option would be to put the match statements into the select clause and reference them in the roder by clause... but I get an error any time I try to use columns function from Query Builder, to add any columns other than aud.*

$builder = $this->di->get('modelsManager')->createBuilder();
$builder->addFrom('AddressUserDetail', 'aud');
$builder->innerJoin('User', 'u.id = aud.userId', 'u');
$builder->leftJoin('PropertyAddress', 'pa.id = aud.addressId', 'pa');
        'u.accountId = :acctId: or (aud.shared <> 0 and ash.userId = :authUid:)',
        [ 'acctId' => $acctId, 'authUid' => $authInfo->uid ]
        'FULLTEXT_MATCH(aud.label, aud.notes, :qStr:) or FULLTEXT_MATCH(pa.street, pa.city, pa.state, pa.zip, :qStr:)',
        ['qStr' => $qStr]

That works great, just can't get the results ordered the way I need.

Thanks! Adam

p.s. Yes I'm using the Incubator to get the FULLTEXT_MATCH function, and yes THAT works fine.

Hi @Oak what do you get if you do this var_dump($builder->getQuery()) and look the pre-builded sql query

How would I BIND the parameters to the ORDER BY clause to figure that out?

edited Jan '18

If I remember well, ORDER BY clause and bound parameters are not supported by PDO.

EDIT: try with this:

$order = 2;

$stmt = $db->prepare("SELECT field from table WHERE column = :param ORDER BY :order DESC");
$stmt->bindParam(':param', $is_live, PDO::PARAM_STR);
$stmt->bindParam(':order', $order, PDO::PARAM_INT);


Bottomline: you need pass the order of column insted of the name (see SO link above)

Of course this is raw PHP PDO example, you need to use it in Phalcon in standard way.

Right, I can execute a raw query no problemo.

But I want to get models back.

As an alternative, I can move the logic into the select....

select      aud.*, FULLTEXT_MATCH(aud.label, aud.notes, :qStr:) + FULLTEXT_MATCH(pa.street, pa.city, pa.state, pa.zip, :qStr:) as rank
order by rank desc

BUT - I believe it's not possible to get models back when adding silly columns like that to the select. Is this correct?