Hey, how can I associate a table with more than just one other table, when the other tables need to use the same foreignKey.
e.g.:
class FramesTable extends Table
{
$this->belongsTo('Articles', [
'foreignKey' => 'item_id',
'joinType' => 'INNER',
]);
$this->belongsTo('Entities', [
'foreignKey' => 'item_id',
'joinType' => 'INNER',
]);
best,
Hmm. That sounds a bit fuzzy to me. A future programmer (or even your future self) might curse you for this choice
What are you actually trying to accomplish with this schema?
well lets say you have a RatingsTable plus functions to rate Cars/Boats and you want to use the same table/functions with your Cars and Boats Table/Controller… e.g.: with ajax…
class RatingsTable extends Table
{
$this->belongsTo('Cars', [
'foreignKey' => 'item_id',
'joinType' => 'INNER',
]);
$this->belongsTo('Boats', [
'foreignKey' => 'item_id',
'joinType' => 'INNER',
]);
I’m probably missing a lot of nuance here but:
In this example, I would see no reason to create the Associations in RatingsTable. My reason being, Ratings serve as enriching/explanatory data for some item/product (Car or Boat). I can’t envision a case where I would have a Rating record independent of any other record, and have a need to find the associated ‘whatever’.
It’s technically possible to ‘need’ this in the case of a generic view or index page for a Rating. But in terms of the meaningful presentation of data in some UI or in a situation where I was gathering data for some programming reason, I don’t ever see getting the data from the Ratings side of the relationship.
As far as I know your could have this code with no problem:
//in class CarsTable {
$this->hasOne('Ratings', [
'foreignKey' => 'rating_id',
]);
//in BoatsTable
$this->hasOne('Ratings', [
'foreignKey' => 'rating_id',
]);
your code was already part of mine but i need the belongsTo’s in the RatingsTable as well, because otherwise it will not be possible to access the Rating through the $boats object…
e.g.: $boats->rating->average…
maybe i will have to write a plugin for the ratings, because i want to reuse the code to calculate average values etc…
I don’t believe that’s true. Have you tried without the associations in Ratings?
Though I can’t lay my hands on code to 100% verify that right this second, I believe there have been several times where I hand created an association definition on one table without the inverse relationships on the other table and everything worked fine.
Your query would be from the Cars or Boats side
$query = $this->VehicleTable
->find()
->contain(['Ratings'])
->where(['some' => 'condition']);
The association definitions in Ratings should only be needed if you wanted to query from that table and include one of the vehicle classes.
1 Like
To be clear, ratings
table would have id
and any rating data fields but no record of what it belongs to; no foreign key field.
Your vehicle class tables would have id
, rating_id
and other needed columns.