【问题标题】:How to eager load only 1 result from many to many relationship Laravel如何从多对多关系中只加载 1 个结果 Laravel
【发布时间】:2020-07-25 12:57:06
【问题描述】:

我怎样才能急切地只加载一个从多对多的关系?

我有两个型号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) 相同,它只会将一个申请人添加到集合中的最后一项,而另一项具有空数组值

谁能帮忙:)

谢谢

【问题讨论】:

标签: laravel eloquent laravel-6


【解决方案1】:

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

这是我的模型

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 );

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-03-27
    • 2015-05-16
    • 1970-01-01
    • 2018-11-09
    • 2016-06-06
    • 2017-10-03
    • 2020-06-06
    • 1970-01-01
    相关资源
    最近更新 更多