You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel中User与Journal的关联实现问题(User属于Account)

User 与 Journal 关联实现方案

你完全可以通过HasManyThrough关联实现需求,只需正确配置外键参数即可,并非仅适用于「User HasMany Accounts」的场景。

关联逻辑

你的模型关系链为:

  • User → 属于单个 Account(User 表含 account_id 外键)
  • Account → 拥有多个 Journal(Journal 表含 account_id 外键)

通过HasManyThrough,User 可以间接获取其所属 Account 下的所有 Journal。

代码实现(以 Laravel ORM 为例)

在 User 模型中添加关联方法:

public function journals()
{
    return $this->hasManyThrough(
        Journal::class,
        Account::class,
        'id',               // 中间模型 Account 的主键,对应 User 表的 account_id
        'account_id',       // 目标模型 Journal 中关联 Account 的外键
        'account_id',       // 当前模型 User 中关联 Account 的外键
        'id'                // 中间模型 Account 的主键,对应 Journal 表的 account_id
    );
}

使用方式

配置完成后,直接通过以下方式获取用户关联的 Journal 集合:

$user = User::find(1);
$userJournals = $user->journals;

内容的提问来源于stack exchange,提问作者Israr ul Hassan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.08 05:22:18