Laravel PIVOT表具有额外的字段并且withCount('table')无法按预期工作 [英] Laravel PIVOT table with extra fields and withCount('table') not working as expected

查看:34
本文介绍了Laravel PIVOT表具有额外的字段并且withCount('table')无法按预期工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的数据库中具有以下结构.

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)
...

这是我模型中的代码:

# User has many licenses
# User has many products through licenses
User
  // User has many licenses.
  public function licenses()
  {
    return $this->hasMany(License::class);
  }

产品型号.

# Product has many licenses
Product
  
  public function licenses()
  {
    return $this-hasMany(License::class);
  }

许可模式

# 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 :: get('/my-products',[ProductController :: class,'index']);

并在产品控制器中

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

使用 $ user-> products 时,我没有从许可证关系中获得任何产品我需要显示该用户产品的许可证计数.我得到的是:产品B共有15个许可证.我得到的是该产品的所有许可数. https://prnt.sc/xyokil

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

推荐答案

我相信您可以在将相关模型加载为

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

这篇关于Laravel PIVOT表具有额外的字段并且withCount('table')无法按预期工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆