【发布时间】: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 有内置函数可以做到这一点,谢谢 :)
-
你可以使用这个答案:stackoverflow.com/questions/64440891/…
标签: laravel eloquent laravel-6