I have a micro application with a few models. These models are mapped out in the database (I use MySQL Workbench). Everything works well except when I call find on my table that has a few HasMany realtionships it only returns the object representing the row for which I have called find. I want it to have collections of the objects that are related as well and I want to return these in a big messy JSON blob. :)
TLDR; I am trying to retrieve related rows and thought it would be done automatically. What am I missing?
Models:
class Budgets extends Model
{
public $id; <--do I really need these in here????
public $name;
public function initialize()
{
$this->hasMany("id", "Expenses", "budgets_id"); <--why is this required when the database has this metadata??? (oh well)
$this->hasMany("id", "Bills", "budgets_id");
}
}
class Expenses extends Model
{
public $id;
public $budgets_id;
public function initialize()
{
$this->belongsTo("budgets_id", "Budgets", "id");
}
}
class Bills extends Model
{
public $id;
public $budgets_id;
public function initialize()
{
$this->belongsTo("budgets_id", "Budgets", "id");
}
}
Controller
function findAction($id){
$budget = Budgets::findFirstById($id);
$json = json_encode($budget, true);
echo $json;exit();
}
Returns:
{"id":"1","name":"TestBudget","users_id":"2","cash":"1900"}
I want it to return the full budget record as defined by the relationship....not just the budget row.
And why isn't the JSON encoded with type names like this (this is what I'm aiming for):
budgets: [
{
id: 1,
name: "TestBudget",
cash: 1900,
bills: [
{ id: 1, name: "Car", amount:300.00 }
]
expenses: [
{ id: 1, name: "Food", amount:175.55 }
]
}
]
Any help or insight is appreciated.