We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

Column selecting from related table in First() function

I would like to select some of the columns that are related to the user table in my database.

I have the following script set up in my model:

$user = Users::find(array(
              "email = :email:",
              'bind' => array('email' => $user_email)
            ));

According to this forum post you can add the 'columns' attribute in the function to get specified columns. How do I select the columns from related tables? Because the following snippet doesn't work:

$user = Users::find(array(
              "email = :email:",
              'bind' => array('email' => $user_email),
              'columns' => 'othertable.columnname'
            ));

I know it is possible with PHQL but I really like the way it could be done without it by just using the "Find" function. Is it even possible without using PHQL?

Find/FindFirst is using phql anyway, you need to use 'Model::query' or query builder



5.9k
Accepted
answer
edited Feb '17

With the help of Wojciech Ślawski I've managed to solve my issue by using the following code:

$this->modelsManager->registerNamespaceAlias('OT', 'Applicationname\Models'); //Needed because I use namespaces for my models
    $user = $this->modelsManager->createBuilder()
      ->from("OT:Users")
      ->addFrom("OT:OtherTable")
      ->columns('column_i_needed')
      ->where("email = :email:", ["email" => $user_email])
      ->getQuery()
      ->execute();