PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, January 16, 2022

[FIXED] Cakephp 3.6 contain

 January 16, 2022     cakephp, cakephp-3.x, contain, model-associations, php     No comments   

Issue

I have on little problem with my Cakephp's project. I have this get function in StudentController for view action.

$student = $this->Students->get($id, [
        'contain' => ['Courses', 'LessonPresences', 'StudentNotes', 'StudentPayments']
    ]);

StudentNotes are added by Users. With the contain I get the StudentNotes with the ID of the user who add this note. How I can get the name of this user ?

Student {#711 ▼ 
+"id": 1
+"name": "John"
+"lastname": "Doe"
+"email": "johndoe@gmail.com"
+"phone": "111222333"
+"address": "Brown Street"
+"add_date": FrozenTime @1531866000 {#347 ▶}
+"sign_date": FrozenDate @1531699200 {#350 ▶}
+"theory_count": 65
+"course_end": null
+"course_id": 1
+"student_notes": array:1 [▼
0 => StudentNote {#607 ▼
  +"id": 1
  +"s_content": "Test student's note"
  +"add_date": FrozenTime @1532677715 {#606 ▶}
  +"student_id": 1
  +"add_user_id": 1

I have "add_user_id" which is "1". How can I get the name of this user? There is an belongsTo association in StudentNotesTable

$this->belongsTo('Users', [
        'foreignKey' => 'add_user_id',
        'joinType' => 'INNER'
    ]);

Solution

simply add 'Users' to the contain array. You can do it in many ways, the following are all equivalent

Using dotted notation

 'contain' => [
    'Courses', 
    'LessonPresences', 
    'StudentNotes', 
    'StudentNotes.Users',
    'StudentPayments',
 ]

Using array

 'contain' => [
    'Courses', 
    'LessonPresences', 
    'StudentNotes' => ['contain' => ['Users']], 
    'StudentPayments',
 ]

Using callable

 'contain' => [
    'Courses', 
    'LessonPresences', 
    'StudentNotes' => function ($q) {
         return $q->contain(['Users']);
    }, 
    'StudentPayments',
 ]


Answered By - arilia
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing