问题描述
这让我感到莫名其妙,看不到任何错误,谷歌没有提供帮助。
我在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表示歉意。