laravel - Laravel - How to extract one field for items in a model to an array?
问题描述
I have a table that has a one-to-many relationship with another table.
Call them tables parent
and child
child
has a field called field1
I am trying to get an array of all field1
values.
In the parent
Model, I have this function that gets me all children of parent
public function children()
{
return $this->hasMany(Child::class);
}
Now, in the parent
model, I also want to get all field1
values.
I can get all the children like so:
$children = $this->children->all();
But I just can't figure out how to then index into this to get all the field1
values.
Maybe it is better to just use $this->children
in which case it is a Collection
and then use some sort of Collection method to extract field1
?
I tried
$this->children->only(['field1'])
but that returned nothing, even though field1 certain exists.
Ideas?
Thanks!
解决方案
You can use pluck method of collecion to get an array of field1 values:
$parent->child->pluck('field1');
Or better, you can use pluck method of query builder (see section Retrieving A List Of Column Values), being even more efficient, with same result:
$parent->child()->pluck('field1');
推荐阅读
- windows - 在文件中搜索三个连续的文本行
- java - 使用包含运算符的字符串作为 if 语句中的变量
- c# - 将 ASP.NET 测试启动类移到项目根目录之外?
- json - 如何在 Golang 服务器中通过 ID 参数返回特定的 JSON 数据
- symfony - 如何仅在嵌入式表单中呈现特定的孙子?
- firebase - 在 NoSQL(Firestore)中检查现有相关文档的有效方法?
- c# - 在扩展方法中使用 Array 和 IEnumerable
- php - 比较控制器上的字符串
- javascript - 如何在 PHP 文件中捕获签名板图像并输出到 HTML 文件(如收据)中,然后将页面存储为 JPEG 或 PDF
- c# - wpf 集合子属性数据绑定路径