多态关联下条件预加载嵌套关联问题:如何同时获取Poll与Banner
问题原因
你两次为postables关联定义预加载闭包,由于数组键重复,后面的闭包会覆盖前面的,最终只执行了筛选postable_type = 'banner'的逻辑,导致Poll类型的Postable数据被过滤。
解决方案
将两种类型的处理合并到一个postables预加载闭包中,通过条件判断为不同类型的Postable加载对应关联数据,或利用Laravel多态关联特性简化查询。
方法一:条件加载关联(严谨版)
use App\Models\Poll; Post::with(['postables' => function ($postableQuery) { $postableQuery->with([ 'postable' => function ($polymorphicQuery) { // 仅当Postable关联的是Poll模型时,加载其Options和Votes $polymorphicQuery->when($polymorphicQuery->getModel() instanceof Poll, function ($query) { $query->with('options.votes'); }); } ]); }])->get();
方法二:直接嵌套加载(简洁版)
由于Banner模型没有options关联,Laravel会自动忽略该关联的加载,不会报错,同时能正确获取Poll的子关联数据:
Post::with('postables.postable.options.votes')->get();
方法三:按类型分开展开加载
如果需要更明确控制不同类型的加载逻辑,可在Postable模型中定义针对性关联后预加载:
- 在
Postable模型中添加两个关联:
public function poll() { return $this->morphOne(Poll::class, 'postable'); } public function banner() { return $this->morphOne(Banner::class, 'postable'); }
- 执行查询:
Post::with([ 'postables.poll.options.votes', 'postables.banner' ])->get();
内容的提问来源于stack exchange,提问作者alcolopa
相关产品推荐
相关产品推荐

