skip to Main Content

I have the following method:

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

That returns the following output:

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

How can I make it return an array of ids for "links" using the "link_id" field value, as in:

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

2

Answers


  1. Try something like:

        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();
            });
        }
    
    Login or Signup to reply.
  2. 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();
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search