gpt4 book ai didi

php - 查询生成器上的未定义关系方法 - Laravel

转载 作者:行者123 更新时间:2023-12-03 19:20:29 26 4
gpt4 key购买 nike

我有 3 个表usersteamsathletes

用户可以是团队或运动员。

我将 user_id 放入 teamsathletes 表中。

我将下面的代码放在 User.php 模型中。

public function team()
{
return $this->hasOne (Team::class);
}


public function athlete()
{
return $this->hasOne (Athlete::class);
}

我把下面的代码放在 Team.php 模型中

public function user()
{
return $this->belongsTo(User::class);
}

我把下面的代码放在 Athlete.php

public function user()
{
return $this->belongsTo(User::class);
}

我在 Controller 中使用以下代码。

$staff_picks = User::notAdmin()->active()->orderBy('id','desc')->take(10)->team()->athlete()->get();

我遇到了错误

laravel.ERROR: Call to undefined method Illuminate\Database\Eloquent\Builder::team()`

知道为什么会这样吗?

最佳答案

好的,所以错误说

Call to undefined method Illuminate\Database\Eloquent\Builder::team()

这意味着 team() 方法未在类 Builder 中定义

现在 Builder 类位于vendor/laravel/framework/src/Illuminate/Database/Eloquent/Builder.php 命名空间Illuminate\Database\Eloquent

从逻辑上讲,名为 team() 的函数不可能存在,对吧?


什么是team()?那么我该如何调用它呢?

team() 是模型 app/User.php 中的一个函数,它返回一个 hasOne 函数

好的,hasOne() 在哪里?

hasOne 是在 vendor/laravel/framework/src/Illuminate/Database/Eloquent/Concerns/HasRelationships.php 命名空间 Illuminate\Database 下的特征\Eloquent\Concerns

See here

namespace Illuminate\Database\Eloquent\Concerns;
// Imports ommitted for brevity

trait HasRelationships
{
// Other methods ommitted for brevity

/**
* Define a one-to-one relationship.
*
* @param string $related
* @param string $foreignKey
* @param string $localKey
* @return \Illuminate\Database\Eloquent\Relations\HasOne
*/
public function hasOne($related, $foreignKey = null, $localKey = null)
{
$instance = $this->newRelatedInstance($related);
$foreignKey = $foreignKey ?: $this->getForeignKey();
$localKey = $localKey ?: $this->getKeyName();
return $this->newHasOne($instance->newQuery(), $this, $instance->getTable() . '.' . $foreignKey, $localKey);
}
// Other methods are omitted for brevity

但是它怎么称呼呢?我没有使用 HasRelationships 特征

没错,app/User.php 类没有使用 HasRelationships 特性,但它扩展了一个使用该特性的类*

use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable

*虽然不是直接的

Illuminate\Foundation\Auth\User extends Illuminate\Database\Eloquent\Model

See Here

namespace Illuminate\Foundation\Auth;

// Other Imports ommitted for brevity
use Illuminate\Database\Eloquent\Model;

class User extends Model implements
AuthenticatableContract,
AuthorizableContract,
CanResetPasswordContract
{
use Authenticatable, Authorizable, CanResetPassword, MustVerifyEmail;
}

Illuminate\Database\Eloquent\Model uses the Concerns\HasRelationships trait

See Here

namespace Illuminate\Database\Eloquent;

// Imports ommitted for brevity

abstract class Model implements Arrayable, ArrayAccess, Jsonable, JsonSerializable, QueueableEntity, UrlRoutable
{
use Concerns\HasAttributes,
Concerns\HasEvents,
Concerns\HasGlobalScopes,
Concerns\HasRelationships, // <-- THERE IT IS HERE!!!!
Concerns\HasTimestamps,
Concerns\HidesAttributes,
Concerns\GuardsAttributes,
ForwardsCalls;
// Rest of class ommitted for brevity

等等!这个类如何知道特征 Concerns\HasRelationships 在没有导入的情况下来自哪里?

因为 Concerns 是附加(或嵌套)到同一命名空间的命名空间,所以此类定义于

这个类在 Illuminate\Database\EloquentHasRelationships 是在 Illuminate\Database\Eloquent\Concerns 所以一个简单的调用 Concerns\HasRelationships 就足够了

现在 HasRelationships trait 中有函数 hasOne

好的,那么如何避免这个错误呢?

确保您是从模型实例而不是查询生成器调用模型中定义的关系

例子

User::where('name', 'John Doe')->teams;

正确

User::where('name', 'John Does')->first()->teams;

但为什么呢?

检索该模型之前,您对该模型所做的任何 SQL 操作都是一个查询生成器实例

但是一旦你通过 first() 获得模型本身,你就可以调用关系

更新:回答问题的具体场景

您可能想要获取多个模型,因此在获取每条记录之后调用关系函数 team() 并不理想

解决方案?

预加载

使用 with 方法将关系数据包含在通过 get() 获取的集合中

示例

假设我有一个 User 和一个 Profile

每个用户都有一个且只有一个配置文件,所以我在 User 模型上定义了一个 hasOne 关系

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

现在我们在迁移中需要一个外键来将profiles 表与users 表相关联

Schema::create('profiles', function (Blueprint $table) {
$table->bigIncrements('id');
$table->integer('age'); // Column to test with
$table->unsignedBigInteger('user_id');
$table->foreign('user_id')->references('id')->on('users');
$table->timestamps();
});

现在让我们播种一些数据

public function run()
{
factory(User::class, 10)->create()->each(function ($user) {
$user->profile()->create(['age' => rand(20, 60)]);
});
}

现在让我们打开 artisan tinker 看看会发生什么

>>> App\User::take(10);
=> Illuminate\Database\Eloquent\Builder {#3067}

take() User 模型上的函数返回一个 Builder 实例

让我们尝试获取关于它的配置文件

>>> App\User::take(10)->profile();

错误

BadMethodCallException with message 'Call to undefined method Illuminate/Database/Eloquent/Builder::profile()'

但现在我们知道为什么了

现在让我们试试预加载

>>> App\User::take(10)->with('profile');
=> Illuminate\Database\Eloquent\Builder {#3056}

返回一个查询生成器

让我们调用 get()

>>> App\User::take(10)->with('profile')->get();

现在我们得到了我们的数据集合

=> Illuminate\Database\Eloquent\Collection {#3070
all: [
App\User {#3022
id: 1,
name: "Augusta Botsford MD",
email: "xwaelchi@example.net",
email_verified_at: "2019-09-30 16:40:12",
created_at: "2019-09-30 16:40:12",
updated_at: "2019-09-30 16:40:12",
profile: App\Profile {#3095
id: 1,
age: 29,
user_id: 1,
created_at: "2019-09-30 16:40:12",
updated_at: "2019-09-30 16:40:12",
},
},
App\User {#3017
id: 2,
name: "Olga Leannon",
email: "ufay@example.com",
email_verified_at: "2019-09-30 16:40:12",
created_at: "2019-09-30 16:40:12",
updated_at: "2019-09-30 16:40:12",
profile: App\Profile {#3096
id: 2,
age: 24,
user_id: 2,
created_at: "2019-09-30 16:40:12",
updated_at: "2019-09-30 16:40:12",
},
},
App\User {#3019
id: 3,
name: "Bria Prosacco DDS",
email: "hartmann.trystan@example.com",
email_verified_at: "2019-09-30 16:40:12",
created_at: "2019-09-30 16:40:12",
updated_at: "2019-09-30 16:40:12",
profile: App\Profile {#3097
id: 3,
age: 43,
user_id: 3,
created_at: "2019-09-30 16:40:12",
updated_at: "2019-09-30 16:40:12",
},
},
App\User {#3054
id: 4,
name: "Clare Bayer",
email: "rosalinda60@example.org",
email_verified_at: "2019-09-30 16:40:12",
created_at: "2019-09-30 16:40:12",
updated_at: "2019-09-30 16:40:12",
profile: App\Profile {#3098
id: 4,
age: 52,
user_id: 4,
created_at: "2019-09-30 16:40:12",
updated_at: "2019-09-30 16:40:12",
},
},
App\User {#3058
id: 5,
name: "Vickie Kub",
email: "katherine.abbott@example.com",
email_verified_at: "2019-09-30 16:40:12",
created_at: "2019-09-30 16:40:12",
updated_at: "2019-09-30 16:40:12",
profile: App\Profile {#3099
id: 5,
age: 42,
user_id: 5,
created_at: "2019-09-30 16:40:12",
updated_at: "2019-09-30 16:40:12",
},
},
App\User {#3059
id: 6,
name: "Tressie Gottlieb",
email: "elmira.osinski@example.net",
email_verified_at: "2019-09-30 16:40:12",
created_at: "2019-09-30 16:40:12",
updated_at: "2019-09-30 16:40:12",
profile: App\Profile {#3100
id: 6,
age: 21,
user_id: 6,
created_at: "2019-09-30 16:40:12",
updated_at: "2019-09-30 16:40:12",
},
},
App\User {#3042
id: 7,
name: "Saige Pollich",
email: "gkemmer@example.org",
email_verified_at: "2019-09-30 16:40:12",
created_at: "2019-09-30 16:40:12",
updated_at: "2019-09-30 16:40:12",
profile: App\Profile {#3101
id: 7,
age: 24,
user_id: 7,
created_at: "2019-09-30 16:40:12",
updated_at: "2019-09-30 16:40:12",
},
},
App\User {#3087
id: 8,
name: "Dr. Emiliano Sauer",
email: "marks.florida@example.net",
email_verified_at: "2019-09-30 16:40:12",
created_at: "2019-09-30 16:40:12",
updated_at: "2019-09-30 16:40:12",
profile: App\Profile {#3102
id: 8,
age: 42,
user_id: 8,
created_at: "2019-09-30 16:40:12",
updated_at: "2019-09-30 16:40:12",
},
},
App\User {#3086
id: 9,
name: "Genoveva Abshire",
email: "colt.harber@example.com",
email_verified_at: "2019-09-30 16:40:12",
created_at: "2019-09-30 16:40:12",
updated_at: "2019-09-30 16:40:12",
profile: App\Profile {#3103
id: 9,
age: 27,
user_id: 9,
created_at: "2019-09-30 16:40:12",
updated_at: "2019-09-30 16:40:12",
},
},
App\User {#3088
id: 10,
name: "Dimitri Moore",
email: "slockman@example.net",
email_verified_at: "2019-09-30 16:40:12",
created_at: "2019-09-30 16:40:12",
updated_at: "2019-09-30 16:40:12",
profile: App\Profile {#3104
id: 10,
age: 30,
user_id: 10,
created_at: "2019-09-30 16:40:12",
updated_at: "2019-09-30 16:40:12",
},
},
],
}

我希望这能消除一些困惑

关于php - 查询生成器上的未定义关系方法 - Laravel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58170942/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com