我是Laravel的新手。我正在尝试制作一个通知和文件模型之间具有一对多关系的应用程序。
noticesAlter表包含notice_subject,additional_data,created_at,updated_at
和文件表包含文件名,notice_id,created_at,updated_at。
其中notice_id是文件表中引用“ 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
我不知道我在做什么错?为什么我没有得到父母通知记录。

最佳答案

您的noticesAlter()方法不返回任何内容(缺少return关键字)。这就是为什么您的错误提示您尝试在get()上调用null的原因,因为如果什么都没返回,noticesAlter()就会返回null

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

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

关于php - 试图在Laravel中以一对多关系查找子记录的父级时为null,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/39513449/

10-14 13:05
查看更多