0

I am using Laravel 5.7 and i have following tables

category

id | category_name 

post_categories

id | category_id | post_id | some other fields

posts

id | post_title

i have belongs to many relationship in category Model

 public function post(){

        return $this->belongsToMany(Post::class,'post_categories','category_id','post_id')
            ->withPivot('col2', 'col3','col4');
    }


$response=Category::with('post')->get();

This will return has expected but now i dont need category detail in my response i mean is it possible to declare relationship in pivot model since i know category_id and i can avoid category detail in my response

my aim is to retrieve all post by category id

scott
  • 3,112
  • 19
  • 52
  • 90
  • Possible duplicate of [Get specific columns using "with()" function in Laravel Eloquent](https://stackoverflow.com/questions/19852927/get-specific-columns-using-with-function-in-laravel-eloquent) – Aydin4ik Oct 14 '18 at 09:55
  • Are you trying to return only post ID's that relate to this category? Can you clarify what exactly you want to get in response? – Aydin4ik Oct 14 '18 at 09:57
  • @Aydin4ik.no i need all post detail and some extra pivot row detial – scott Oct 14 '18 at 09:59
  • @Aydin4ik.its not duplicate since post belongs to more than one category – scott Oct 14 '18 at 10:00

1 Answers1

2

You can use select() function on 'Category' to remove unnecessory columns.

Note that 'id' of the category table is important, since it is used in the pivot table as foreign key.

// this will only get the id of the category
// and all the post and pivot data.
$response = Category::select('id')->with('post')->get();
Tharaka Dilshan
  • 4,371
  • 3
  • 14
  • 28