php 使用“with”语句获取id数组而不是数组对象

vecaoik1  于 2023-09-29  发布在  PHP
关注(0)|答案(2)|浏览(96)

我有以下方法:

public static function list()
    {
        return static::with(['links' => function($query) {
            $query->select('link_id');
        }])->get();
    }

它返回以下输出:

"objects": [
   {
      "id": 6,
      "links": [
         {
            link_id: 6,
            pivot: {
               object_id: 6,
               link_id: 6
            }
         },
         {
            link_id: 7,
            pivot: {
               object_id: 6,
               link_id: 7
            }
         }
      ]
   }
]

如何使用“link_id”字段值使其返回“links”的id数组,如:

"objects": [
   {
      "id": 6,
      "links": [6, 7]
   }
]
a1o7rhls

a1o7rhls1#

public static function list()
{
    $objects = static::with(['links' => function($query) {
        $query->select('link_id');
    }])->get();

    // Iterate through the objects and pluck the link_ids
    $result = $objects->map(function ($object) {
        return [
            'id' => $object->id,
            'links' => $object->links->pluck('link_id')->toArray(),
        ];
    });

    return $result->toArray();
}
cbeh67ev

cbeh67ev2#

尝试以下操作:

public static function list()
    {
        return static::with(['links' => function($query) {
            $query->select('link_id');
        }])->get()->each(function ($model) {
            $model->links = $model->links->pluck('link_id')->toArray();
        });
    }

相关问题