Reputation: 216
I've started to learn programming with Phalcon a few weeks ago and I have a question about the relationships, which are used for 'easy' programming.
The setup I've got a table full with products (Products model obvious), a table with categories (Category model) and a table with subcategories (Subcategory model). A product CAN be in a category or a subcategory (depends if the category has subcategories).
So, I've currently got 4 models
- Product (matches with id)
- Category (matches with id)
- Subcategory (matches with id)
- CatRelation (used for linking the products)
The CatRelation table contains a:
- productId
- satId
- subId
Where the catId/subId cannot be filled both.
So, when I'm in a category, I want to use the model to fetch all the products within that category by catId. The same goes for the subcategory.
My current models look like this:
class Product extends ModelBase
{
public $id;
public $name;
/**
* @return string
*/
public function getSource()
{
return "products";
}
public function initialize()
{
$this->hasMany("id", "CatRelation", "productId");
}
}
class Category extends ModelBase
{
/**
* @return string
*/
public function getSource()
{
return "categories";
}
public function initialize()
{
$this->hasMany("id", "CatRelation", "catId");
}
}
class Subcategory extends ModelBase
{
/**
* @return string
*/
public function getSource()
{
return "subcategories";
}
public function initialize()
{
$this->hasMany("id", "CatRelation", "subId");
}
}
class CatRelation extends ModelBase
{
public $id;
public $productId;
public $catId;
public $subId;
/**
* @return string
*/
public function getSource()
{
return "productCatRelations";
}
public function initialize()
{
$this->belongsTo("productId", "Product", "id");
$this->belongsTo("catId", "Category", "id");
$this->belongsTo("subId", "Subcategory", "id");
}
}
I hope someone out there is willing to help me out! :) If you have some suggestions, please suggest them! I'm still learning, so that's only helping me.
Cheers.
Upvotes: 2
Views: 3010
Reputation: 1759
I never worked with belongsTo
, but can you try a many-to-many relationship in Category Model.
$this->hasManyToMany("id", "CatRelation", "catId",
"productId", "Product", "id",['alias' => 'Product']);
Then, if you want to get all the products for each category, try:
$rows = Category::query()->execute();
foreach($rows as $row)
{
var_dump($row->Product->toArray());
}
Upvotes: 1