Skip to content
Advertisement

How do I traverse CakePHP relations?

I’m trying to traverse the relations on CakePHP models. This is the database: My database

I can access product attributes (product->attributes) on a product model but I cannot access the product attributes on Ad model (ad->product->attributes).

Here is my code:

JavaScript

And here is what I do in the views:

JavaScript

What is wrong? How do I access the relation Ad->product->attribute from my Ad model?

Advertisement

Answer

Perhaps the problem could be that you’re not using CakePHP’s conventions.

From the docs:

“new join table’s name needs to include the names of both models involved, in alphabetical order, and separated with an underscore ( _ ).”

So, your join table should be named attributes_products.

Also, check your foreign keys. They should be in singular form.

  • attributes_products.id
  • attributes_products.product_id
  • attributes_products.attribute_id

Hopefully that solves the problem.

References:

http://book.cakephp.org/2.0/en/models/associations-linking-models-together.html#hasandbelongstomany-habtm

http://book.cakephp.org/2.0/en/getting-started/cakephp-conventions.html#model-and-database-conventions

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement