返回值必须是 ?Illuminate\\Database\\Query\\Builder, App\\Models\\ModelName 返回的类型

2024-05-06

我试图得到以下回应:

"user": {
        "id": 1,
        "first_name": "john",
        "last_name": "doe",
        "email": "[email protected] /cdn-cgi/l/email-protection",
        "phone_number": "12345678",
        "email_verified_at": null,
        "created_at": "2021-09-02T08:57:07.000000Z",
        "updated_at": "2021-09-02T08:57:07.000000Z",
        "country": {
                     "id": 1,
                     "name": "UK",
                     "phone_code": 44
                    } 
    }

代替:

"user": {
        "id": 1,
        "first_name": "john",
        "last_name": "doe",
        "email": "[email protected] /cdn-cgi/l/email-protection",
        "phone_number": "12345678",
        "email_verified_at": null,
        "created_at": "2021-09-02T08:57:07.000000Z",
        "updated_at": "2021-09-02T08:57:07.000000Z",
        "country_id": 1
    }

为了做到这一点,我在用户模型中使用了一个 mutator 函数:

public function getCountryIdAttribute(): Builder|null
{
   return Country::where('id', $this->attributes['country_id'])
    ->get()
    ->first();
}

但是,国家/地区表已在外部数据库中找到,我已正确设置其连接。

但我按照这个创建了国家模型Laravel 文档 https://laravel.com/docs/8.x/eloquent:

use Illuminate\Database\Eloquent\Model;

class Country extends Model
{
/**
 * The database connection that should be used by the model.
 *
 * @var string
 */
protected $connection = 'my second db connection name';

/**
 * The table associated with the model.
 *
 * @var string
 */
protected $table = 'countries';

/**
 * The primary key associated with the table.
 *
 * @var string
 */
protected $primaryKey = 'id';

/**
 * The model's default values for attributes.
 *
 * @var array
 */
protected $attributes = [
    'id',
    'name',
    'phone_code',
];
}

当我尝试获取用户时,出现以下错误:

{
"error": [
    "App\\Models\\User::getCountryIdAttribute(): Return value must be of type ? 
    Illuminate\\Database\\Query\\Builder, App\\Models\\Country returned"
],
"message": "Unhandled server exception",
"code": 500
}

我试图尽可能多地解释我的情况。 感谢您的帮助。


问题是你在函数中说getCountryIdAttribute它返回Builder | null。当你这样做时

   return Country::where('id', $this->attributes['country_id'])
    ->get()
    ->first();

它将返回一个实例Country or null。要解决您的问题,您应该将返回类型更新为Country | null:

public function getCountryIdAttribute(): Country | null
{
   return Country::where('id', $this->attributes['country_id'])
    ->get()
    ->first();
}

Laravel 提供了使用的方法关系 https://laravel.com/docs/8.x/eloquent-relationships#one-to-one这将极大地提高您的代码性能。在这种情况下你可以这样做:

public function country()
{
  return $this->hasOne(Country::class, 'country_id');
}

然后在获取时users你可以做:

$users = User::where(...)->with('country')->get();

这将阻止您的代码N+1 https://medium.com/doctolib/understanding-and-fixing-n-1-query-30623109fe89#:%7E:text=TL%3BDR%3A%20The%20N%2B,%E2%80%9CHow%20to%20fix%20it%3F%E2%80%9D问题。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

返回值必须是 ?Illuminate\\Database\\Query\\Builder, App\\Models\\ModelName 返回的类型 的相关文章

随机推荐

  • 静态方法而不是原型方法Javascript

    当在类中调用实例函数时 对象的每个实例都会获得自己的函数副本 但在原型方法和静态方法中不会创建副本 它们属于类 所以如果它们都没有创建其函数的副本 那么为什么如果我们不想复制 可以简单地使用原型方法 那么我们是否有静态函数 我有点困惑 如果
  • 使用 SimpleXML 从 XML 获取多个项目

    我正在尝试使用下面的代码循环 XML 中的多个项目 xml get data the url data simplexml load string xml foreach data gt item AS item foreach item
  • 在 iOS 8 上本地化用户

    你好 我开始将我的应用程序移植到 iOS 8 但很快我就遇到了 CLLocationManager 的问题 基本上 该应用程序不再将地图集中在用户位置上 而是提出错误 尝试启动 MapKit 位置更新而不提示位置授权 必须首先调用 CLLo
  • Jasmine的spyOn()是否允许执行spies on函数?

    茉莉花有吗spyOn 方法允许执行监视函数 或者确实是这样 当 即将 调用监视方法时拦截调用 并返回true PS 谁能给我解释一下spyOn 的内部运作 Spy 间谍可以伪装成一个函数或一个对象 您可以在编写单元测试代码时使用它们来检查函
  • 'NSDate' 没有可见的 @interface 声明选择器 'initWithString:' [重复]

    这个问题在这里已经有答案了 可能的重复 NSDate initWithString https stackoverflow com questions 7770257 nsdate initwithstring 我写了下面一行代码 NSDa
  • 翻转旋转和图像

    我正在用 Java 编写一个平台游戏 并且正在手动编码玩家动画 我分别为每个肢体设置动画 改变位置和旋转 当玩家面向右时 这工作得很好 但是当玩家面向左时 我不知道如何处理旋转 以使它们在玩家向左转时看起来相同 每个身体部位的位置都是相对于
  • 有没有办法使用 Mayavi 填充陀螺仪表面的一侧?

    我正在使用 Mayavi 绘制陀螺仪的等值面 我的问题是我需要通过填充两个生成区域的一侧来获得更坚固的结构 在下面的图片中 您可以看到我生成的等值面的外观以及填充一侧后的外观 我生成的等值面 它应该是什么样子 等值面可以通过以下方程生成 U
  • Swift 中的 NSCollectionView 选择处理

    使用 Swift 学习 我一整天都在做这件事 但进展甚微 需要知道何时选择 NSCollectionView 中的项目 最终目标是让项目突出显示 并能够使用删除键将其从集合中删除 我的 NSCollectionView 绑定到 ArrayC
  • 在 eclipse indigo 中找不到 Window builder pro

    我读到 Eclipse Indigo 安装了 Window Builder Pro 插件 但我不知道它在哪里 文件 新建 项目没有给我选择 Window Builder Pro 的选项 如何找到它 您需要将此更新站点添加到 Eclipse
  • Font Awesome 4.0.0 缺少图标

    是我一个人的问题 还是 FontAwesome 3 x x 中实际上有 FontAwesome 4 0 0 中缺少的图标 如果是这样 这肯定会让 FontAwesome 对我来说不再那么棒 例如 我似乎找不到相当于icon remove 没
  • java格式化表格输出

    所以我正在尝试格式化我的输出 System out println Menu nItem tItem t tPrice tQuantity for int i 0 i
  • jQuery 单击事件更改 php 会话变量

    对此最好的方法是什么 因为 正如我发现的 只有在尝试过之后才完全有意义 p 你不能在 javascript 条件下设置 PHP 变量 杜尔赫 我能想到的唯一解决方案是对一个处理会话变量的小型 PHP 文件进行 AJAX 调用 elm cli
  • 给定字符串的所有可能排列?

    我该如何在 Ruby 中做到这一点 p abc all possible permutations 将返回 abc acb bca bac cba cab Edit 感谢雅库布 汉普尔 class String def all possib
  • 仅以 int 形式显示和保存小时数

    如何仅显示小时并使用 int 变量 我的意思是打印时间 例如 20 30 44 PM 我只想存储小时 即 int 变量中的 20 小时 怎么做 有谁知道的话可以告诉我密码吗 谢谢 尝试使用日历get http docs oracle com
  • 无法让 Rails Server 与 MySQL 一起使用

    我正在尝试让我的 Rails 应用程序与 MySQL 一起使用 而不是默认的 SQLite 我创建了一个新项目 强制使用 MySQL 它似乎工作正常 它在 Gem 文件中添加了 gem 条目 如下所示 source https rubyge
  • StateObject 作为 init() 中另一个对象的参数

    我试图将 StateObject 用户传递给authenticationHelper 但我不能 因为 IDE 说 在初始化所有存储的属性之前使用 self 即使它是在结构体的开头初始化的 我考虑过将 user 的初始化移至 init 但同样
  • Windows批处理编程中的用户输入操作

    我想以 ddmmyyyy 格式接受用户的输入 当用户以这种格式输入日期时 文件将移动到相应的文件夹 我尝试了以下代码但失败了 SET p str 输入文件夹的名称 例如30062011 移动 C Documents and Settings
  • 如何从图书馆创建承诺

    我对此感到困惑 因为到目前为止我发现的每个教程都假设我可以编辑库代码 或者库只有回调或回调作为最后一个参数 我正在使用的库的每个功能都设置为function successCallBack result FailCallBack error
  • java中使用awt.Toolkit和Clipboard是否可以知道剪贴板中复制的内容是否是mp3文件

    我正在尝试编写一个运行于背景 and monitors复制 a 的复制操作 mp3 file or a 文件夹包含 a mp3 file Clipboard cb Toolkit getDefaultToolkit getSystemCli
  • 返回值必须是 ?Illuminate\\Database\\Query\\Builder, App\\Models\\ModelName 返回的类型

    我试图得到以下回应 user id 1 first name john last name doe email email protected cdn cgi l email protection phone number 12345678