0
votes

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

1
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
@Aydin4ik.no i need all post detail and some extra pivot row detialscott
@Aydin4ik.its not duplicate since post belongs to more than one categoryscott

1 Answers

2
votes

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