- because you are not loading users table
Nov 12, 2024
5
Level 13
limit fields returned by belongsToMany() with paginate()
Is there a way how I can limit the fields, being returned from a relation of type belongsToMany()?
Assume this relation inside User model class
public function favouriteSellers()
{
return $this->belongsToMany('App\Models\User', 'favourite_sellers', 'user_id', 'seller_id');
}
Using
$items = $items = Auth::user()->favouriteSellers()
->select('favourite_sellers.user_id', 'users.name',
'users.slug') // fields to retrieve
->join('seller_users', 'favourite_sellers.seller_id', '=',
'seller_users.user_id') // Join with sellerUsers
->withCount([
//some relations we count...
'confirmedProducts',
])
->latest('pivot_created_at')->get();
returns the collection with fields as requested:
#attributes: array:8 [▼
but when I change get() to paginate() ALL attributes of the User model are inlcuded:
#attributes: array:34 [▼
My main questions are:
1.) Why did I need to write favourite_sellers.user_id instead of users.id? For other fields (!= id) it's not required?
2.) Why did paginate() cause laravel to load all attributes of the model even if I specified to load only defined attributes?
Please or to participate in this conversation.