繁体   English   中英

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

[英]Laravel one to many relationship - “Illuminate\\Database\\Eloquent\\RelationNotFoundException”

这让我感到困惑,看不出有什么问题,谷歌也没有帮助。

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

我不断收到以下错误:

"message": "调用模型 [App\\EmailServiceType] 上未定义的关系 [services]。", "exception": "Illuminate\\Database\\Eloquent\\RelationNotFoundException", "file": "/home/vagrant/Code/WebDevMarket/供应商/laravel/framework/src/Illuminate/Database/Eloquent/RelationNotFoundException.php", "line": 34, "trace": [

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

应用\\电子邮件服务.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();
    }
}

应用\\电子邮件服务类型.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', 'type_id', '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 排序。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM