Laravel一对多关系-“ Illuminate \\ Database \\ Eloquent \\ RelationNotFoundException”

问题描述

这让我感到莫名其妙,看不到任何错误,谷歌没有提供帮助。

我在Laravel的EmailService模型和EmailServiceType模型中有一对多的关系。

我不断收到以下错误:

“ message”:“调用模型[App \ EmailServiceType]上的未定义关系[服务]。”, “ exception”:“ Illuminate \ Database \ Eloquent \ RelationNotFoundException”, “文件”:“ / home / vagrant / Code / WebDevMarket / vendor / laravel / framework / src / Illuminate / Database / Eloquent / RelationNotFoundException.php”, “行”:34, “跟踪”:[

下面是我的模型和控制器功能:

App \ EmailService.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class EmailService extends Model
{
    public function type()
    {
        return $this->belongsTo('App\EmailServiceType','type_id','id')->withTimestamps();
    }
}

App \ EmailServiceType.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class EmailServiceType extends Model
{
    public const SES = 1;
    public const SENDGRID = 2;
    public const MAILGUN = 3;
    public const POSTMARK = 4;
    public const MAILJET = 5;

    /** @var array */
    protected static $types = [
        self::SES => 'SES',self::SENDGRID => 'Sendgrid',self::MAILGUN => 'Mailgun',self::POSTMARK => 'Postmark',self::MAILJET => 'Mailjet',];

    /**
     * Resolve a type ID to a type name.
     */
    public static function resolve(int $typeId): ?string
    {
        return static::$types[$typeId] ?? null;
    }

    public function services()
    {
    return $this->hasMany('App\EmailService','id')->withTimestamps();
    }    
}

EmailServiceController.php函数

public function GetTypes()
    {

        $Type = EmailServiceType::with('services')->get();

        return EmailServiceResource::collection($Type);
    }

非常感谢您提前提供任何帮助。

解决方法

您不需要提供参考ID,请尝试以下操作:

    public function services()
    {
      return $this->hasMany('App\EmailService');
    }     
,

原来是withTimestamps()的使用;造成问题的原因。这是仅用于数据透视表的laravel方法。

对在laracasts中的isamaile表示歉意。

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...