我有以下代码
$user = User::findByAccountCode($transaction->account_code);
当我在 phpunit 上执行这段代码时,它返回一个 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() 的调用所做的) - 他们只允许通过添加/删除约束来更新查询。
代替
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();
如果你想在你的 中有一个方法用户 将返回给定帐户代码的用户的方法,可以随意创建它,但不要以 开头它的名称范围 ,例如:
public static function findByAccountCode($account_code){
return static::where('account_code', $account_code)->first();
}
这样,您的代码将按您的意愿工作 - 调用以下命令以获取单个用户:
$user = User::findByAccountCode($transaction->account_code);
关于php - 使用 phpunit 时, Eloquent 查询范围返回构建器而不是模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38951160/