Laravel PIVOT table with extra fields and withCount('table') not working as expected

廉价感情. 提交于 2021-02-10 14:14:53

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!