Eloquent 查询范围 return 使用 phpunit 时生成器而不是模型

Eloquent Query Scope return Builder instead of Model when using phpunit

我有以下代码

$user = User::findByAccountCode($transaction->account_code);

当我在 phpunit 上执行这段代码时,它 returns 一个 Illuminate\Database\Eloquent\Builder 的实例而不是用户模型。

这是 findByAccountCode

的代码
public function scopeFindByAccountCode($query,$account_code){


   return $query->where('account_code', $account_code)->first();

}

我的应用程序出现以下错误

ErrorException: Argument 1 passed to aunicaj\Libraries\MarkupRepository::user() must be an instance of aunicaj\Models\User, instance of Illuminate\Database\Eloquent\Builder given

当我使用浏览器时它工作正常但在 phpunit 上不行。谢谢

您使用的查询范围不正确。他们永远不应该获取任何记录(这就是您对 first() 的调用正在做的事情)——他们只允许使用 adding/removing 约束更新查询。

替换

public function scopeFindByAccountCode($query,$account_code){
  return $query->where('account_code', $account_code)->first();
}

public function scopeFindByAccountCode($query,$account_code){
  return $query->where('account_code', $account_code);
}

并像下面这样在任何地方使用它:

$user = User::findByAccountCode($transaction->account_code)->first();

如果你想在你的 User 方法中有一个方法可以 return 给定帐户代码的用户,请随意创建它,但不要其名称以 scope 开头,例如:

public static function findByAccountCode($account_code){
  return static::where('account_code', $account_code)->first();
}

这样您的代码将按您希望的方式运行 - 调用以下命令以获得单个用户:

$user = User::findByAccountCode($transaction->account_code);

我的问题解决了原来我在测试中使用的工厂方法是

factory(User::class)->make() 

应该是

factory(User::class)->create()