I am creating a matchmaking service on my website.
I have 5 tables: Buyers, Sellers, Categories, buyer_categories(Pivot), seller_categories(Pivot).
Users will be creating an account as a BUYER, selecting 5 categories they are looking to buy in. The data of what categories they have selected will be stored in the buyer_categories table with: id
,buyer_id
,category_id
.
Users will be creating an account as a SELLER, selecting 5 categories they are looking to sell in. The data of what categories they have selected will be stored in the seller_categories table with: id,seller_id,category_id.
What I need is a way of displaying pulling the data so that it shows you matched buyers/sellers that have selected the same categories as you. Matching buyers to sellers and vice versa.
What makes it more tricky as the way it needs to be displayed is ranked by those who match the most categories as you have.... as I want to display it like this.
"These buyers have matched 5 of your selected categories" ... ... ... ... "These buyers have matched 4 of your selected categories" ... ... ... ETC.
Any advice or ideas?
You could do something like this: (I dont know if syntax is correct for many to many relationship, but the idea is there :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()
will show count of matching categories of user and seller