HasMany关联时怎么多字段关联?

例子,我的主表post对应多个资源contents, 这样写没问题

public function contents(): HasMany
{
    return $this->hasMany(Content::class, 'post_id', 'post_id');
}

甚至我还可以带条件

public function contents(): HasMany
{
    return $this->hasMany(Content::class, 'post_id', 'post_id')->where('status', 'active');
}

但是,我的A可以反复修改,并且我要记录每个修改的版本,于是post与contents表加上了version_id,每次修改自增,contents只增加不修改删除,按post表的version_id对应即可

我尝试这样做

public function contents(): HasMany
{
    return $this->hasMany(Content::class, 'post_id', 'post_id')->where('version_id', $this->version_id);
}

发现version_id是null的

    // 这样写没问题,但是因为还没有查询出数据,不知道version_id是多少
    $post = Post::with(['publisher', 'contents'=>function($query){
        $query->where('version_id', 16);
    }])->where('post_id', $post_id)->first();

只能手动另外查吗, 还是有什么好办法可以使用laravel自带的关联

还有个办法, 但需要再写一行

$post->contents()->where('version_id', $post->version_id)->get();
本作品采用《CC 协议》,转载必须注明作者和本文链接
:) wink
唐章明
《L02 从零构建论坛系统》
以构建论坛项目 LaraBBS 为线索,展开对 Laravel 框架的全面学习。应用程序架构思路贴近 Laravel 框架的设计哲学。
《L01 基础入门》
我们将带你从零开发一个项目并部署到线上,本课程教授 Web 开发中专业、实用的技能,如 Git 工作流、Laravel Mix 前端工作流等。
讨论数量: 2

contents 方法中的$this 此阶段属性值并未填充所以调用$this->version_id 得到的值为空, 可以尝试自行实现多字段模型关联或使用扩展包,参考老帖子:问答:Laravel 如何实现 relationship 多字段关联?

12小时前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!