【问题标题】:Laravel PIVOT table with extra fields带有额外字段的 Laravel PIVOT 表
【发布时间】:2021-02-01 07:50:21
【问题描述】:

我的数据库中有以下结构。

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);
  }
  
  // User has many products
  // Expected: products
  // Outcome: not getting
  public function products()
  {
     return $this->belongsToMany(Product::class, 'licenses', 'user_id', 'product_id')
            ->using(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();
    
    // This doesn't get any products. Which is what I want to use.
    $products = $user->products;
    
    // This works but I want to display more efficiently and using less DB query. 
    $licenses = $user->licenses;
    $products = [];
    foreach ($licenses as $license) {
        array_push( $products, $license->product)
    }
    
    // Get unique products of an user through licenses relation.
    $products = collect($products)->unique();
  }

使用$user->products 时,我没有从许可关系中获得任何产品 如果页面中有超过 5 个产品,我想对产品进行分页,并减少额外的数据库查询和模型加载层。请建议一些更好的方法。

【问题讨论】:

    标签: php eloquent pivot-table relationship laravel-8


    【解决方案1】:

    我建议通过许可对属于用户的产品执行单独的单一查询

    $products = Product::whereHas('licenses.user', function (Builder $query) use($user) {
                           $query->where('id', $user->id);
                         })->paginate(5);
    

    或

    $products = Product::whereHas('licenses', function (Builder $query) use($user) {
                           $query->where('user_id', $user->id);
                         })->paginate(5);
    

    这样,您不必遍历所有数据来从延迟加载的关系中提取产品,也不需要独特的操作

    【讨论】:

    • 还有一个问题:我们可以通过```$user->products()```方式让它工作吗? ??顺便说一句,只是好奇。
    • @Raajen 是的,但这可能包含基于不同许可证的重复产品
    • @md-khalid-junaid 抱歉打扰你了。只需要另一个帮助prntscr.com/xyokil。我使用了 ->withCount(['licenses']) ,但不是显示用户为此产品购买的实际许可证数量,而是显示整体许可证。
    • 嗨@Raajen 如果您可以提出一个新问题,其中包含查看/调试问题所需的所有相关详细信息,那就太好了
    • 这里是新问题的链接:stackoverflow.com/questions/65990717/…
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-16
    相关资源
    最近更新 更多