G.J
G.J

Reputation: 465

CakePHP-3.0 multiple belongsTo associations

I'm having following tables, Issues, Users, Reasons and Images. Basically Issues have many Reasons and my goal is to display the attachment image of the 'Reasons' as well as the author of the post (Users).

1. Users table associated with Reasons
2. Both Users and Reasons are associated with Images table (foreign key 'image_id').

It works in find query when associating

'Reasons.Images' or 'Reasons.Users.Images'

But not both! This is my code, which returns only for 'Reasons.Images'.

$this->Issues->findById($id)->contain([
    'Reasons.Images',
    'Reasons.Users.Images'
]);
So how I get the Image association of both the tables or Should my approach be different?

Upvotes: 1

Views: 560

Answers (1)

G.J
G.J

Reputation: 465

I managed to resolve this issue!! Using associations in proper order would solve the issue.
This is the main response from Issues table.

Array
     (
        [id] => 2
        [content] => This is an issue!!
        [reason_id] => 3
        [image_id] => 15
        [user_id] => 21
     )

To fix issues in retrieving images of the issue([image_id] => 15) as well as user's avatar image (for [user_id] => 21), I just rephrased the associations (Reasons, Images and Users) in reverse order of the above response...

$this->Issues->findById($id)->contain([
'Reasons.Images',
'Reasons.Users.Images',
'Reasons.Users => function($t){
    return $t
      ->select(['user_id','username','image_id']);
}
]);

This works perfect as expected! May be could help someone else at some point!! Thanks!!

Upvotes: 4

Related Questions