laravel - 是否可以从 Laravel 中的 hasmany 关系中返回特定的索引元素?
问题描述
$row->sub_category[0]->name
当我检查其他问题时,我可以看到有访问第一个和最后一个元素的选项,但是有没有办法访问基于数组索引值的元素。
我需要在一个hasmany关系中获得第n个项目(你知道n),并且会在没有foreach循环的情况下直接获得它(不加载其他关系元素)。
解决方案
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
推荐阅读
- ruby-on-rails - rails activerecord where 子句如何接受动态参数?
- sql - 在存储过程中将 varchar 转换为数字时出错
- javascript - 将数据传递给 v-model
- kotlin - 为什么 mutableSet 不更新!用于 Kotlin 列表中的项目
- angular - 包含换行符的字符串在 webapi 中出现没有换行符
- google-app-engine - 部署到 Google 应用引擎 (Java) 后,找不到 MemcacheServiceFactory 类错误
- c# - 如何通过 c# 从 1400 万个表中删除 100,000 个特定行?
- php - 属于子类别的某些帖子未显示在此 if 语句中
- ruby-on-rails - SQS 池的启动/停止如何在 Ruby on Rails 中工作
- r - 如何在 R 中对数据进行子集化