Laravel 如何从多对多关系中只加载1个结果

Laravel 如何从多对多关系中只加载1个结果,laravel,eloquent,laravel-6,Laravel,Eloquent,Laravel 6,如何从多对多关系中仅加载一个 我有两种型号申请和申请人 Models\Application.php public function applicants() { return $this->belongsToMany(Applicant::class); } public function oneApplicant() { return $this->applicants()->first(); } 我想对申请进行分页,只想加载一个申请者(如果他们有) 但

如何从多对多关系中仅加载一个

我有两种型号
申请
申请人

Models\Application.php

public function applicants() {
    return $this->belongsToMany(Applicant::class);
}

public function oneApplicant() {
    return $this->applicants()->first();
}
我想对申请进行分页,只想加载一个申请者(如果他们有)

但它不起作用。 像这样获得第一个结果
return$this->applicators()->first()
将生成对undefined method\Database\Query\Builder::with()调用的错误

如果我也设置了一个限制而不是第一个
return$this->applications()->limit(1)
它将只显示最后一个集合的一个申请者

我还尝试直接在急切加载调用时修改查询,以获得第一行

return Application::with(['applicants',  => function( $query ) {
        $q->first();
    }])->orderBy('created_at','desc')->paginate( $count );
但结果与直接在关系上添加
限制(1)
相同,它只会将一个申请者添加到集合中的最后一个项目,而另一个项目的数组值为空

有人能帮忙吗:)


谢谢

我意识到它太复杂了,我自己无法实现,最后使用了来自的软件包(非常感谢他,节省了我的工作时间:)

这是我的模型

类应用程序扩展了BaseModel{
使用\staudenMir\elounceTeagerLimit\hasWangerLimit;
公共职能申请者(){
返回$this->belongtomany(申请人::类);
}
公共职能一申请人(){
返回$this->applicators()->limit(1);
}
}
然后我就可以在我的控制器上使用它了

returnapplication::stage($stages)
->stagenot($stagenot)
->参考($refered,$term)
->与([
“一个申请人”,
'一个申请人。一个电话:型号识别号,号码',
'一个申请人。一个地址:州型号\ id'
])->orderBy('created_at','desc')->paginate($count);

我意识到这太复杂了,自己无法实现,最终使用了来自的软件包(非常感谢他,节省了我的工作时间:)

这是我的模型

类应用程序扩展了BaseModel{
使用\staudenMir\elounceTeagerLimit\hasWangerLimit;
公共职能申请者(){
返回$this->belongtomany(申请人::类);
}
公共职能一申请人(){
返回$this->applicators()->limit(1);
}
}
然后我就可以在我的控制器上使用它了

returnapplication::stage($stages)
->stagenot($stagenot)
->参考($refered,$term)
->与([
“一个申请人”,
'一个申请人。一个电话:型号识别号,号码',
'一个申请人。一个地址:州型号\ id'
])->orderBy('created_at','desc')->paginate($count);

看看这个有趣的软件包,我认为它没有那么复杂,laravel有内置函数来做,谢谢:)你可以用这个答案:看看这个有趣的软件包,我认为它没有那么复杂,laravel有内置函数来做,无论如何,谢谢:)您可以使用以下答案:
return Application::with(['applicants',  => function( $query ) {
        $q->first();
    }])->orderBy('created_at','desc')->paginate( $count );