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

How to eager load only 1 result from many to many relationship Laravel

我怎样才能只加载多对多关系中的一个?

我有两个模型 Application & Applicant

Models\Application.php

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

public function oneApplicant() {
    return $this->applicants()->first();
}

我想对申请进行分页,并且只想加载一个申请人(如果他们有的话)。

return Application::stage( $stages )
->stagenot($stageNot)
->refered( $refered, $term )
->with(['oneApplicant'])
->orderBy('created_at','desc')->paginate( $count );

但它不起作用。 得到这样的第一个结果 return $this->applicants()->first() 将产生错误 Call to undefined method Illuminate\Database\Query\Builder::with()

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

我还尝试直接在预加载调用上修改查询以获取第一行

return Application::with(['applicants',  => function( $query ) {
        $q->first();
    }])->orderBy('created_at','desc')->paginate( $count );

但结果与直接在关系上添加 limit(1) 相同,它只会将一个申请人添加到集合中的最后一项,而另一项的数组值为空

谁能帮忙:)

谢谢

我意识到自己实现它太复杂了,最终使用了 eloquent-eager-limit package from staudenmeir(非常感谢他,节省了我的工作时间:))

这是我的模型

class Application extends BaseModel {
    use \Staudenmeir\EloquentEagerLimit\HasEagerLimit;

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

    public function oneApplicant() {
        return $this->applicants()->limit(1);
    }
}

然后我就可以在我的控制器上使用它了

return Application::stage( $stages )
    ->stagenot($stageNot)
    ->refered( $refered, $term )
    ->with([
        'oneApplicant',
        'oneApplicant.onePhone:model_id,number',
        'oneApplicant.oneAddress:model_id,state'
    ])->orderBy('created_at','desc')->paginate( $count );