首页 文章

尝试在laravel中的一对多关系中查找子记录的父级时获取null

提问于
浏览
0

我是Laravel的新手 . 我正在尝试创建一个应用程序,其中通知和文件模型之间存在一对多的关系 . noticesAlter表包含notice_subject,additional_data,created_at,updated_at和files表包含filename,notice_id,created_at,updated_at . 其中notice_id是files表中引用'noticesAlter'表中'id'的外键

这是我的模特

class noticesAlter extends Model
{
    protected $table = 'noticesalter';
    protected $fillable = ['notice_subject', 'filename', 'additional_details'];
    public function Files()
    {
        return $this->hasMany('App\Files', 'notice_id', 'id');
    }
}

class Files extends Model
{
    protected $table = 'files';
    protected $fillable = ['notice_id', 'filename'];
    public function noticesAlter()
    {
        $this->belongsTo('App\noticesAlter', 'notice_id', 'id');
    }
}

当我尝试通过修补程序找到id = 29的通知文件时,我得到了所需的结果,即我的所有文件都将notice_id = 29作为外键 . First Attached Image正如您在图像中看到的那样,我得到一个id = 45且notice_id = 29的文件 .

但是当我试图找到同一个文件的父通知时,我得到一个空对象,这个Second Attached Image我不知道我在做什么错?为什么我没有收到父通知记录 .

1 回答

  • 1

    您的 noticesAlter() 方法没有返回任何内容(缺少 return 关键字) . 这就是为什么你的错误说你试图在 null 上调用 get() ,因为 noticesAlter() 如果没有返回则返回 null .

    更新您的方法以返回关系:

    public function noticesAlter()
    {
        return $this->belongsTo('App\noticesAlter', 'notice_id', 'id');
    //  ^^^^^^
    }
    

相关问题