Laravel 在 Eloquent 中使用 with() 方法时出错

Laravel error using with() method in Eloquent

我试图在 Laravel Eloquent ORM 中使用 with() 方法调用,但出现以下错误。

Argument 1 passed to App\Http\Controllers\DashboardController::App\Http\Controllers\{closure}() must be an instance of Illuminate\Database\Eloquent\Builder, instance of Illuminate\Database\Eloquent\Relations\HasMany given

我使用的是最新版本的 Laravel 6。知道是什么原因造成的吗?

控制器

class DashboardController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth:api');
    }

    public function formIndex(Request $request)
    {
        $id = auth()->user()->id;
        $item = Groupe::find($id)->with(
            [
                'etudiants' => function (Builder $query) {
                    $query->select('id');
                }
            ]
        )->first();

        return $item;
    }
}

型号

class Groupe extends Authenticatable implements JWTSubject
{
    public function etudiants()
    {
        return $this->hasMany('App\Etudiant');
    }
}

但是你想要什么return? groupe->students[]??你可以使用

    $item = Groupe::where('id',$id)->with('etudiants')->first();

错误来自您对 $query 变量的类型提示,因为错误消息说传入的对象是一种关系,而不是原始查询生成器。只需删除类型提示。 ::find() 也执行一个查询,所以你正在执行 2 个查询,请改用下面的查询

Groupe::where('id', $id)->with(['etudiants' => function ($query) {
        $query->select('id');
    }])->first();

此外,您不需要使用回调语法来仅急切加载某些列,回调语法用于限制返回记录。试试这个。

Groupe::where('id', $id)->with('etudiants:id,name,email')->first();