首页 > 解决方案 > 是否可以从 Laravel 中的 hasmany 关系中返回特定的索引元素?

问题描述

$row->sub_category[0]->name

当我检查其他问题时,我可以看到有访问第一个和最后一个元素的选项,但是有没有办法访问基于数组索引值的元素。

我需要在一个hasmany关系中获得第n个项目(你知道n),并且会在没有foreach循环的情况下直接获得它(不加载其他关系元素)。

标签: laraveleloquentrelationshiphas-many

解决方案


If you want the N-th item of a relationship without loading all other elements you can (probably) use query:

$nthSubcategory = $row->sub_category()->skip($n-1)->first()

If it doesn't exist then $nthSubcategory will end up being null


推荐阅读