【问题标题】:Cakephp 3.6 containCakephp 3.6 包含
【发布时间】:2019-01-04 07:51:18
【问题描述】:

我的 Cakephp 项目有点问题。 我在 StudentController 中有这个 get 函数用于查看操作。

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

StudentNotes 由用户添加。通过包含,我得到了带有添加此注释的用户 ID 的 StudentNotes。我怎样才能得到这个用户的名字?

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

我有“add_user_id”,即“1”。我怎样才能得到这个用户的名字? StudentNotesTable

中有一个 belongsTo 关联
$this->belongsTo('Users', [
        'foreignKey' => 'add_user_id',
        'joinType' => 'INNER'
    ]);

【问题讨论】:

    标签: php cakephp model-associations cakephp-3.x contain


    【解决方案1】:

    只需将'Users' 添加到包含数组。可以通过多种方式实现,以下都是等价的

    使用点分符号

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

    使用数组

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

    使用可调用对象

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

    【讨论】:

      猜你喜欢
      • 2019-02-01
      • 2011-07-29
      • 2019-02-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-18
      • 2011-04-26
      相关资源
      最近更新 更多