首页 > 解决方案 > 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!

标签: laravel

解决方案


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');

推荐阅读