Hello,
So lets say I have 2 tables in database : users and users images, and I want to pull data from those tables and output with my API in json .. (using transformer to output data in json). For some reason I can get data from table users with no problem, but when i try to pull from both tables im getting same data again, only from users table .. So I want to get this data : user 'id' and 'name' from users table and image 'path' from that users images table..
So here is app structure:
-
Controllers - UsersContoller.php
-
Models - UsersModel.php UsersImageModel.php
-
Processors -
- Transformers - UsersTransformer.php
//MODELS
UsersModel.php
<?php
use Phalcon\Mvc\Model;
class UsersModel extends Model
{
public $id;
public $name;
public function initialize()
{
$this->setSource('users');
$this->hasMany("id", "UsersImage", "users_id");
}
}
UsersImageModel.php
<?php
use Phalcon\Mvc\Model;
class UsersImageModel extends Model
{
public $id;
public $users_id;
public $path;
public function initialize()
{
$this->setSource('users_images');
$this->belongsTo("users_id", "Users", "id");
}
}
//CONTROLLERS
UsersControllers.php
class UsersController extends BaseController
{
public function indexAction()
{
try {
$Users = UsersModel::find();
$this->api->withCollection($users, new UsersTransformer())->send();
} catch(Exception $e) {
$this->api->withException($e)->send();
}
}
//TRANSFORMERS
UsersTransformer.php
class UsersTransformer extends TransformerAbstract
{
public function transform(UsersModel $users)
{
return [
'id' => (int)$users->getId(),
'name' => $users->getName(),
'image' => $users->getPath()
];
}
}