我是 Laravel 的新手。我正在尝试创建一个应用程序,其中通知和文件模型之间具有一对多的关系。 notificationAlter 表包含 notification_subject、additional_data、created_at、updated_at 文件表包含文件名、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 的修补程序查找通知文件时,我得到了所需的结果,即所有将 notification_id = 29 作为外键的文件。 First Attached Image 正如您在图片中看到的那样,我得到了一个 id=45 且 notification_id = 29 的文件。
但是当我尝试查找同一文件的父通知时,我得到一个空对象,并且这个 Second Attached Image 我不知道我做错了什么?为什么我没有收到家长通知记录。
最佳答案
您的 noticesAlter()
方法未返回任何内容(缺少 return
关键字)。这就是为什么您的错误表明您尝试在 null
上调用 get()
,因为 noticesAlter()
返回 null
如果没有返回任何内容。
更新您的方法以返回关系:
public function noticesAlter()
{
return $this->belongsTo('App\noticesAlter', 'notice_id', 'id');
// ^^^^^^
}
关于php - 尝试在 Laravel 中的一对多关系中查找子记录的父记录时获取 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39513449/