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.
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;
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With