kappa
kappa

Reputation: 107

how to get only ids from a related model

I have Product Model and Size Model. It is a many to many relationship. What I am trying to do right now is that I want to return product data with an array of related size model's ids like below.

"data": [ { "id": 1, "name": "サンプル商品名", "product_code": "1ZS2fmMGEK", "material": "サンプル素材", "category_id": 1, "desc": "Tempore illum eum quia nihil iste neque eligendi. Est velit maiores vero animi debitis. Quae est nihil quo odio. Consequatur dicta at sit quas iste velit. Mollitia ut aut est perspiciatis.", "views": 0, "purchase_count": 0, "created_at": "2021-01-26T11:07:58.000000Z", "updated_at": "2021-01-26T11:07:58.000000Z", "sizes": [1,2,3,4,5 ] },

So I wrote my code like this.

public function getAll(Array $query):object
{
    try {
        $products = Product::query();
        if($query['sort']){
            $sort_field = $query['sort'][0];
            $order = $query['sort'][1];
            $products->sortable([$sort_field => $order]);
        }
        if($query['filter']){
            $field_name = key($query['filter']);
            $value = $query['filter'][$field_name];
            $products->where($field_name, 'like', '%'.$value.'%');
        }

        return $products->with(['sizes' => function($query){
                $query->select('sizes.id');
                 }])->paginate(10);

     
         
       

    } catch (\Throwable $e) {
        // 全てのエラー・例外をキャッチしてログに残す
        \Log::error($e);

        // フロントに異常を通知するため例外はそのまま投げる
        throw $e;
    }
}

However, it returned the size's data like this.

"sizes": [ { "id": 1 }

this is not what I want, as I want an array of ids like this.

"sizes": [1, 2, 3, 4, 5]

So I tried to change my code and wrote this but no luck.

return $products->with(['sizes' => function($query){
     $query->pluck('sizes.id');
  }])->paginate(10);

Does anyone have an idea of how to do this?

Upvotes: 1

Views: 960

Answers (1)

kappa
kappa

Reputation: 107

return $products->paginate(10)->through(function ($product, $key) {
            $product['sizes'] = $product->sizes()->pluck('sizes.id');
            $product['colors'] = $product->colors()->pluck('colors.id');
            return $product;
         });

this code worked for me

Upvotes: 1

Related Questions