【问题标题】:Laravel: How to compare 2 pivot tables and display matchesLaravel:如何比较 2 个数据透视表并显示匹配项
【发布时间】:2020-08-16 02:19:42
【问题描述】:

我正在我的网站上创建配对服务。

我有 5 个表:Buyers、Sellers、Categories、buyer_categories(Pivot)、seller_categories(Pivot)。

用户将作为买家创建一个帐户,选择他们想要购买的 5 个类别。他们选择的类别的数据将存储在买家类别表中:id,buyer_id,@987654323 @。

用户将作为卖家创建一个帐户,选择他们希望销售的 5 个类别。他们选择的类别的数据将存储在 Seller_categories 表中:id、seller_id、category_id。

我需要一种显示拉取数据的方式,以便它显示您匹配的买家/卖家选择了与您相同的类别。将买家与卖家匹配,反之亦然。

是什么让它变得更棘手,因为它需要显示的方式是由与你拥有的最多类别匹配的人排名的......因为我想这样显示它。

“这些买家匹配了您选择的 5 个类别” ……………… “这些买家匹配了您选择的 4 个类别” ………… 等等。

有什么建议或想法吗?

【问题讨论】:

    标签: laravel eloquent eloquent-relationship


    【解决方案1】:

    你可以这样做: (我不知道多对多关系的语法是否正确,但想法就在那里:D)

    $buyerCategories = $user->categories()->pluck('id')->toArray();
    
    $sellers = Seller::whereHas( //this will get only sellers with al least one same category as $user
                         'categories', 
                         function($q) use ($buyerCategories) 
                         {
                             $q->whereIn('id', $buyerCategories);
                         }
                     )
                     ->with([ //this will select only categories same as $user
                         'categories' => 
                         function($q) use ($buyerCategories) 
                         {
                             $q->whereIn('id', $buyerCategories);
                         }
                      ])
                      ->get();
    

    $sellers->categories->count() 将显示用户和卖家匹配类别的计数

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-07
      • 1970-01-01
      • 2017-07-29
      • 1970-01-01
      • 2013-08-21
      • 2018-08-20
      相关资源
      最近更新 更多