CakePHP 5.x:如何获取BelongsToMany关联中间表的额外字段
解决BelongsToMany关联中中间表额外字段的访问问题
方式一:关联查询时显式加载中间表字段
你需要在查询用户关联通知时,明确指定要包含中间表的额外字段,否则这些字段不会被自动注入到_matchingData中。以常见的ORM框架(如CakePHP)为例,查询代码可以这么写:
// 获取用户#1及其关联通知,同时加载中间表字段 $user = $this->Users->get(1, [ 'contain' => [ 'Notifications' => [ 'UsersNotifications' => [ 'fields' => ['is_read', 'reading_datetime'] ] ] ] ]);
也可以在模型关联定义阶段,默认设置包含这些字段,避免每次查询都手动指定:
// 在UsersTable的initialize方法中配置关联 $this->belongsToMany('Notifications', [ 'through' => 'UsersNotifications', 'fields' => ['is_read', 'reading_datetime'] ]);
配置完成后,就能通过通知对象的_matchingData访问中间表字段了:
foreach ($user->Notifications as $notification) { $isRead = $notification->_matchingData['UsersNotifications']->is_read; $readingDatetime = $notification->_matchingData['UsersNotifications']->reading_datetime; }
方式二:直接查询中间表(按需选择)
如果你的需求仅关注用户与通知的关联状态(比如已读状态、阅读时间),或者需要更灵活的查询条件,直接查询UsersNotifications表会更高效:
// 查询用户#1的所有通知关联记录,可选包含通知内容 $userNotifications = $this->UsersNotifications->find() ->where(['user_id' => 1]) ->contain(['Notifications']) // 如果需要同时获取通知详情,保留此行 ->all();
这种方式下,每条结果直接携带is_read、reading_datetime字段,无需通过_matchingData间接访问。
内容的提问来源于stack exchange,提问作者Mirko Pagliai
相关产品推荐
相关产品推荐

