簡體   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