1
votes

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?
1
I don't really get your answer and how this solves anything. Why does your issue response have a reason_id when this should be a Issue hasMany Reason association? Also the order is the same as in your question, you've just added another containment (respectively containment configuration)? Besides that, the find in your question works fine for me as is, the result will contain the reasons with their associated image and user, where the users have their image included too.ndm
@ndm: May be my way of explaining was unclear for you. I should have posted my faulty responses before. But basically, for the find that I had questioned...I did not get the 'Images' when I got 'Users.Images'...And this is a part of my main association that I'm working. So When I figured out the proper way of using associations (like I mentioned in my answer) I was able to retrieve data as expected. So I just posted my answer.G.J

1 Answers

4
votes

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!!