【问题标题】:Laravel - Method Illuminate\Support\Collection::select does not existLaravel - 方法 Illuminate\Support\Collection::select 不存在
【发布时间】:2021-05-27 13:40:12
【问题描述】:

我正在尝试获取选定的列而不是完整的列。

$profiles= auth()->user()->profile()->where('id', $id)->select('profile.id','profile.name');

还有我的profile() 方法

public function profile()
{
    return $this->hasMany(Profile::class)->get();
}

如果我删除->select('profile.id','profile.name'),它会返回profile 表的完整列,但我只想要其中的几列。如果我添加 ->select() 它会给我以下错误:

BadMethodCallException:方法 Illuminate\Database\Eloquent\Collection::select 不存在。在文件中

请建议更改方法调用。谢谢。

【问题讨论】:

  • 收集助手laravel.com/docs/8.x/collections没有这种方法可以使用
  • 这就是你没有把->get()放在hasMany()之后的原因;您完全删除了链接查询的能力,例如select()where() 等,因为您正在立即执行查询。仔细检查文档laravel.com/docs/8.x/eloquent-relationships,在hasOne()hasMany()belongsTo() 等之后,没有一个示例函数使用->get()->first(),现在你知道为什么了:)

标签: php laravel eloquent


【解决方案1】:

get()select()(在profile())之前被调用,这是错误的,因为你试图在获取的Collection 上调用select() 方法。所以从你的关系函数中删除get()

public function profile()
{
    return $this->hasMany(Profile::class);
}

注意:如果您在其中使用 get(),请对 user() 执行相同操作。

【讨论】:

    【解决方案2】:

    您可以尝试将->select('profile.id','profile.name') 更改为->pluck('profile.id','profile.name') 吗?

    【讨论】:

      猜你喜欢
      • 2020-08-16
      • 2021-09-27
      • 2021-10-25
      • 2019-12-06
      • 2020-11-20
      • 2022-01-22
      • 2020-06-09
      • 2021-04-27
      • 2019-05-25
      相关资源
      最近更新 更多