Laravel:如何比较 2 个数据透视表并显示匹配项

Laravel: How to compare 2 pivot tables and display matches

我正在我的网站上创建婚介服务。

我有 5 个 table:买家、卖家、类别、buyer_categories(枢轴)、seller_categories(枢轴)。

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

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

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

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

"These buyers have matched 5 of your selected categories" ……………… "These buyers have matched 4 of your selected categories" ………… 等等

有什么建议或想法吗?

你可以这样做: (我不知道多对多关系的语法是否正确,但想法是存在的: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() 将显示用户和卖家匹配类别的计数