7.3. 发表回复 Web 开发实战进阶 ( Laravel 6.x ) 字段缓存为空

app\Observers\ReplyObserver.php 中按照课程所写

<?php

namespace App\Observers;

use App\Models\Reply;

class ReplyObserver
{
    public function creating(Reply $reply)
    {
        $reply->content = clean($reply->content, 'user_topic_body');
    }

    public function created(Reply $reply)
    {
        // $reply->topic->increment('reply_count', 1);
        $reply->topic->reply_count = $reply->topic->replies->count();
        $reply->topic->save();
    }
}

打印$reply可以获取数据

7.3. 发表回复 |《L02 Laravel 教程 - Web 开发实战进阶 ( Laravel 6.x )》字段缓存数据为空

但是无法获取 $reply->topic 下数据

7.3. 发表回复 |《L02 Laravel 教程 - Web 开发实战进阶 ( Laravel 6.x )》字段缓存为空

直接使用 $reply->topic->replies->count(); 会报错

7.3. 发表回复 |《L02 Laravel 教程 - Web 开发实战进阶 ( Laravel 6.x )》字段缓存数据为空

已经检查 Topic Model 和 Reply Model,代码同教程,请问有其他人遇到这个问题吗

以下为现在的模型类代码:

Reply

<?php

namespace App\Models;

class Reply extends Model
{
    protected $fillable = ['content'];

    public function topic()
    {
        return $this->belongsTo(Topic::class);
    }

    public function user()
    {
        return $this->belongsTo(User::class);
    }
}

Topic

<?php

namespace App\Models;

class Topic extends Model
{
    protected $fillable = [
        'title', 'body', 'category_id', 'excerpt', 'slug'
    ];

    public function replies()
    {
        return $this->hasMany(Reply::class);
    }

User

<?php

namespace App\Models;

use Illuminate\Contracts\Auth\MustVerifyEmail as MustVerifyEmailContract;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Illuminate\Auth\MustVerifyEmail as MustVerifyEmailTrait;

class User extends Authenticatable implements MustVerifyEmailContract
{
    use Notifiable, MustVerifyEmailTrait;

    protected $fillable = [
        'name', 'email', 'password','introduction','avatar'
    ];

    protected $hidden = [
        'password', 'remember_token',
    ];

    protected $casts = [
        'email_verified_at' => 'datetime',
    ];

    //新增用户模型与话题模型的关联
    public function topics(){
    return $this->hasMany(Topic::class);
    }

    //新增因控制器反复调用的获取用户id方法
    public function isAuthorOf($model){
    return $this->id == $model->user_id;
    }

    public function replies()
    {
        return $this->hasMany(Reply::class);
    }
}
《L03 构架 API 服务器》
你将学到如 RESTFul 设计风格、PostMan 的使用、OAuth 流程,JWT 概念及使用 和 API 开发相关的进阶知识。
《G01 Go 实战入门》
从零开始带你一步步开发一个 Go 博客项目,让你在最短的时间内学会使用 Go 进行编码。项目结构很大程度上参考了 Laravel。
讨论数量: 1

模型关联都写好了,按道理$reply->topic应该有数据的。怀疑你是否开启了opcache,或者其他什么因素导致模型关联的修改没有更新到。

4年前 评论
nullable (楼主) 4年前

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