为什么值一直是 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

《L05 电商实战》
从零开发一个电商项目,功能包括电商后台、商品 & SKU 管理、购物车、订单管理、支付宝支付、微信支付、订单退款流程、优惠券等
《L02 从零构建论坛系统》
以构建论坛项目 LaraBBS 为线索,展开对 Laravel 框架的全面学习。应用程序架构思路贴近 Laravel 框架的设计哲学。
最佳答案

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

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

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

5年前 评论

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

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

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