CakePHP 3 associations : Multiple data in one table

Tarikul Islam
Oceanize Lab Geeks
Published in
2 min readSep 26, 2017

I have 2 types of category product-category, and blog-category, How can i use one table for those 2 or more categories ?

There are 3 tables categories, products, and blogs, I want to keep both blog-category and product-category into the categories table and I will call it by cakephp 3 associations.

There will be different data into categories with alias [blog, product].

Categories table Data

Now will define the relations Like

  1. Blogs belongsTo BlogCategories
  2. Products belongsTo ProductCategories
belongsTo Relation in Blogs Table
belongsTo Relation in Product Table

In this relation definitions there are 2 things have to focus className and conditions array

  1. className indicate which class is used for this relations, in my situation i use Categories table class.
  2. Conditions accepts as array of property for joining conditions with category class

if you want more check BelongsTo Associations

Now if i query

Blog category query form BlogsController

It will get all the data which have blog alias in categories Table

BlogCategory query result

Same way we can get ProductCategories data also.

We can keep such different types data into one table using CakePHP 3 associations

--

--