为什么值一直是 null

TestPsy 与 TestReply 关系如下

TestPsy.php

public function testreplies()
    {
        return $this->hasMany(TestReply::class);
    }

TestReply.php

public function testpsy()
    {
        return $this->belongsTo(TestPsy::class);
    }

数据可以成功提交到数据库里,但是用Observer处理的时候, $testreply->testpsy 这个是null,导致报错

TestReplyObserver.php

public function created(TestReply $testreply)
    {
        $testreply->testpsy->reply_count = $testreply->testpsy->testreplies->count();
        $testreply->testpsy->save();
    }

我想问问,$testreply->testpsy里的testpsy是不是就是models里的TestPsy?这个dd出来应该是一个完整的数组才对,但是现在是null

《L01 基础入门》
我们将带你从零开发一个项目并部署到线上,本课程教授 Web 开发中专业、实用的技能,如 Git 工作流、Laravel Mix 前端工作流等。
《L03 构架 API 服务器》
你将学到如 RESTFul 设计风格、PostMan 的使用、OAuth 流程,JWT 概念及使用 和 API 开发相关的进阶知识。
最佳答案

在 tinker 中,$testreply->testpsy 拿出来有值吗?

4年前 评论
wongvio (楼主) 4年前
ㅤㅤ (作者) 4年前
wongvio (楼主) 4年前
ㅤㅤ (作者) 4年前
ㅤㅤ (作者) 4年前
wongvio (楼主) 4年前
讨论数量: 3
public function testpsy()
{
    return $this->belongsTo(TestPsy::class)->withDefault();
}
4年前 评论
wongvio (楼主) 4年前

求助各位大佬,看看我哪里写错了

4年前 评论

在 tinker 中,$testreply->testpsy 拿出来有值吗?

4年前 评论
wongvio (楼主) 4年前
ㅤㅤ (作者) 4年前
wongvio (楼主) 4年前
ㅤㅤ (作者) 4年前
ㅤㅤ (作者) 4年前
wongvio (楼主) 4年前

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