Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Join multiple tables in PHALCON FRAMEWORK

Tags:

php

mysql

phalcon

I am trying to join two tables(MYSQL) in Phalcon framework.

"Table" names:

user
contact_details

"Model" names:

User
ContactDetails

Initialize:

In "User" model ----->$this->hasMany("id", "ContactDetails", "user_id"); 
In "ContactDetails" model----->$this->belongsTo("user_id", "User", "id");

My code:

public function userDetails(){             
      $phql = "SELECT User.*, ContactDetails.* FROM User LEFT JOIN ContactDetails";
      $user = $this->modelsManager->executeQuery($phql);
      -------
      -------Remaining code---------
      --------------
      }
Thanks in advance.
like image 279
Natarajan Srikanta Avatar asked Mar 08 '26 21:03

Natarajan Srikanta


2 Answers

Thanks for the quick reply.

I actually need to run an MySQL query instead of using built-in functions.

Here is the fix which I finally got:

$query = "SELECT u.*, c.* FROM user u "
              . "LEFT JOIN ContactDetails c "
              . "ON c.user_id = u.id ORDER BY u.id ";
      $cars = $this->modelsManager->executeQuery($query);
      $user = array();      
      foreach ($cars as $car) {
        //print_r($car);exit;
          $user[$car->u->id]['firstname'] = $car->u->firstname;
          $user[$car->u->id]['lastname'] = $car->u->lastname;
          $user[$car->u->id]['username'] = $car->u->username;
          $user[$car->u->id]['emailid'] = $car->u->emailid;
          $user[$car->u->id]['address'] = $car->c->address;
          $user[$car->u->id]['street'] = $car->c->street;
          $user[$car->u->id]['city'] = $car->c->city;
      }
like image 83
Natarajan Srikanta Avatar answered Mar 10 '26 12:03

Natarajan Srikanta


This is not tested but it might give you the idea, you don't actually need to use $phql as the model should hold everything you need.

$users = User::find();

foreach($users as $user) {
    // whatever you want
    echo $user->name;

    foreach($user->contactdetails as $contactDetails) {
        echo $contactDetails->telephone;
    }
}

You can get all this information from the docs - http://docs.phalconphp.com/en/latest/reference/models.html

like image 38
Oliver Bayes-Shelton Avatar answered Mar 10 '26 12:03

Oliver Bayes-Shelton



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!