Kiruaaa
Kiruaaa

Reputation: 301

Cakephp - How to get data from other model using associated model?

How to Join two model table to get user name base on user_id?

likesTable.php - id | post_id | user_id

              1      5     23

postTable.php - id | like_id | user_id | content

               5     1    23    Hello
               

userTable.php - id | user_name |

               23  sample_name

PostController

   $this->paginate = [
        'contain' => ['Users', 'Likes'],
    ];
    $posts = $this->paginate($this->posts);

Cake PHP variables in view

 'likes' => object(App\Model\Entity\likes) id:4 {
 'id' => (int) 1
 'post_id' => (int) 5
 'user_id' => (int) 23   ***I want to get user name from this ID***

Upvotes: 1

Views: 44

Answers (1)

Alimon Karim
Alimon Karim

Reputation: 4469

Add users with likes in container (Likes.Users)

$this->paginate = [
        'contain' => ['Users', 'Likes.Users'],
];

Upvotes: 3

Related Questions