Given a simple blog engine that has posts and tags related to posts. There are two tables in the database: Postand Tag, as well as a table PostTagfor many-to-many relationships.
I have a list of tags and I want to find all posts that have all of these tags (so .IsIn()it doesn't work here)
Question: how can I achieve this using nhibernate? (ideally using the method .QueryOver<>())
The problem here is that I donβt even know where to start and how to implement it in pure SQL. I have 2 ideas:
- Retrieve all messages and then filter them using LINQ (i.e. using a function
.IsSupersetOf()) - When using SQL
WHERE EXISTSfor each item in a list
But I believe there is a more elegant way
Table structure
CREATE TABLE Post (
Id INT PRIMARY KEY,
Title NVARCHAR(255) NOT NULL
);
CREATE TABLE Tag (
Id INT PRIMARY KEY,
Tag NVARCHAR(50) NOT NULL
);
CREATE TABLE PostTag (
PostId INT NOT NULL REFERENCES Post(Id),
TagId INT NOT NULL REFERENCES Tag(Id)
);
INSERT INTO Post(Id, Title) VALUES (1, 'Post A');
INSERT INTO Post(Id, Title) VALUES (2, 'Post B');
INSERT INTO Post(Id, Title) VALUES (3, 'Post C');
INSERT INTO Tag(Id, Tag) VALUES (1, 'tagA');
INSERT INTO Tag(Id, Tag) VALUES (2, 'tagB');
INSERT INTO PostTag (PostId, TagId) VALUES (1, 1);
INSERT INTO PostTag (PostId, TagId) VALUES (2, 2);
INSERT INTO PostTag (PostId, TagId) VALUES (3, 1);
INSERT INTO PostTag (PostId, TagId) VALUES (3, 2);
And I want to receive a message with identifier 3 on the specified list of tag identifier: (1, 2)
source
share