问题
I've the following structure in my database.
users
--
id
...
products
--
id
...
licenses (pivot table with some extra informations these data are grabbed via API)
--
user_id
product_id
license_key
license_type
url
purchased_at (datetime)
supported_until (datetime)
...
And here are codes in my model:
# User has many licenses
# User has many products through licenses
User
// User has many licenses.
public function licenses()
{
return $this->hasMany(License::class);
}
Product Model.
# Product has many licenses
Product
public function licenses()
{
return $this-hasMany(License::class);
}
License Model
# License belongs to an user.
# License belongs to a product.
License
public function user()
{
return $this->belongsTo(User::class);
}
public function product()
{
return $this->belongsTo(Product::class);
}
Route
// These class namespaces are imported and all the necessary middlewares are applied.
Route::get('/my-products', [ProductController::class, 'index']);
And in product controller
ProductController
public function index()
{
$user = Auth::user();
$products = Product::whereHas('licenses', function (Builder $query) use($user) {
$query->where('user_id', $user->id);
})
->withCount(['licenses']) // This is returning all the licenses for this product disrespecting the user.
->paginate(5);
}
I'm not getting any products from the licenses relation when using $user->products
I need to display the licenses count for this product of the user.
What I'm getting is: Product B has all total 15 licenses.
What I'm getting is all the licenses count for this product. https://prnt.sc/xyokil
回答1:
I believe you can introduce a closure method to filter for a specific user while loading related models as
$products = Product::whereHas('licenses', function (Builder $query) use($user) {
$query->where('user_id', $user->id);
})
->withCount(['licenses' => function ($query) use ($user) {
$query->where('user_id', $user->id);
}])
->paginate(5);
来源:https://stackoverflow.com/questions/65990717/laravel-pivot-table-with-extra-fields-and-withcounttable-not-working-as-expe