I have table structure as follows
table user: iduser, firstName, lastName, username, email, dateJoined, dateOfBirth, password
table tag : idtag, tagName
table post: idpost, title, content, iduser, date, dateCreated
table post_tag : idpost, idtag :-join table for many to many relationship for tag and post
table user_tag : iduser, idtag :-join table for many to many relationship for user and tag
what i want is the names of the tags for a specific user using JPA query.
I also wanted to retrieve the post for the user and I could retrieve that using the following NamedQuery
SELECT p FROM Post p WHERE p.user = :user ORDER BY p.dateCreated DESC
using this, I was successfully able to retrieve posts for the user as Post and user are both entities and is a valid JPA query
But when I try to retrieve the tags for a specific just like I retrieved posts for user,
so I tried to write a join query something like this
SELECT t.tagName FROM tag t JOIN user_tag ut ON ut.idtag = t.idtag JOIN user u ON ut.iduser = u.iduser WHERE u.username = :username
but eclipse complaints for this query as user_tag is not the entity type. I am not able to formulate a join query using JPA QL which can retrieve tags for a user
Any help is highly appreciated.
I was able to formulate the query as follows
SELECT tag.tagName FROM Tag tag WHERE tag.users = :users
This was just like the query I used for Post and User
but I have another doubt that if we don't need to write a join query in this case, then in which scenarios JPA QL join queries are used?
Related
I have a table in DynamoDB.
student_id, name, age, address partition_key: student_id, table_name: students
lets say student ids are 1,2,3 etc...
I wanted to query students based on Ids.
eg sql select * from students where id in (1,2,3)
How to do the same in DynamoDB
Please help me with the query params.
I tried
params = {
:table_name=>"students",
:key_condition_expression=>"student_id IN :student_id",
:expression_attribute_values=>{":student_id"=> [1,2,3]}
}
DynamoDB does not allow you to apply conditionals around the partition key (e.g. PK in [1,2,3]), you need to specify it explicitly. However, you can perform various condition operations around sort keys (<,>, begins_with, etc).
If you can identify the primary key, which I'm assuming is your student_id and you want students with id 1, 2, and 3, then you can use the client batch_get_item().
There are 2 tables : User and Teacher. Teacher.user_id is from User. So, how do I find in a single query, all the users who are not in teachers.
I meant something along the lines :
User.not_in(Teacher.all)
You can use where.not query from ActiveRecord try something like below:
User.where.not(id: Teacher.pluck(:user_id).reject {|x| x.nil?})
Note: used reject method, in case you have nil values in some records.
The other users seem to have neglected the rails 3 tag (since removed based on the approved answer. My answer left for posterity) : Please try this
User.where("id NOT IN (?)",Teacher.pluck(:user_id).join(","))
This will become SELECT * FROM users WHERE id NOT IN (....) (two queries one to get the user_id from teachers and another to get the user(s) not in that list) and may fail based on the size of teacher table.
Other option is an arel table:
users = User.arel_table
User.where(users[:id].not_in(Teacher.select(:user_id).where("user_id IS NOT NULL")))
This should produce a single query similar to
SELECT * FROM users
WHERE id NOT IN ( SELECT user_id FROM teachers WHERE user_id IS NOT NULL)
(one query better performance) * syntax was not fully tested
Another single query option might be
User.joins("LEFT OUTER JOIN teachers ON teachers.user_id = users.id").
where("teachers.user_id IS NULL")
I think you should be able to do something like this
User.where.not(id: Teacher.ids)
I have a form which has fields from around three tables, and user can fill in any field and they can make a search.
For example i have these table and columns
Vehicle:
rego_num
make
model
vin
engine_num
transmission, ...
Customer:
name
surname
email_address
Address:
address1
address2
address3
phone
work_num
primary_num
fax
Vehicle belongs_to Customer
Customer has_one address
User can make search in any of the above mentioned fields, for ex they can enter rego alone and find serch or rego with make and model or name alone or with phone,
they can enter partial phone number and it should find it, phone is integer column.
I thought of finding vehicle column, if vehicle exist and then find customer, but the problem is they can enter customer fields alone.
I think i can write a joins and do a where query, like
vehicle.joins(:customer)
but address is related to vehicle, Can anyone suggest me how to send params to search method and write a query to find records
I checked pg_search gem it has one keyword to search against multiple columns, but i have multiple value to search against the particular column.
You can use ajax call to send parameters, and in controller you need to create a query with sql.
eg:
get the all params into loacal variables or you can use directly.
reg_no = params[:reg_no]
make = params[:make]
query = 'where '
if reg_no.present?
query = query+ "reg_no ilike #{reg_no} AND "
if make.present?
query = query + "make ilike #{make} AND "
use "=" is user enters "entire string" if it is partial use "ilike".
now you can use join and use the where condition.
may anybody help me with this task...
persistence provider is eclipselink 2.6.
i want to retrieve a list of users that may have 0 or n documents. because both tables have a few columns i want to use SELECT NEW Entity (userId, amountDocuments), i only need the user-id and the amount of documents for this task. if the user hasn't any documents yet, "0" should be shown, e.g.:
UserId: 1 2 3 4
AmountDocs: 0 1 0 3
Mapping for Documents in Entity User is as follows:
#OneToMany(fetch=FetchType.LAZY, cascade=CascadeType.ALL,mappedBy = "user", targetEntity = UserDocument.class)
#OrderBy("sortOrder ASC")
#JoinFetch(JoinFetchType.OUTER)
protected List<UserDocument>documents;
Mapping for User in Entity UserDocument is as follows:
#ManyToOne(cascade=CascadeType.ALL)
protected User user;
and here is the jpa-query:
SELECT DISTINCT
NEW user.entity.User(u.id,count(doc.user)) FROM User u
LEFT JOIN u.documents doc ON doc.user = u
AND doc.active = 't'
GROUP BY u.id
Problem is, that i only retrieve those two users who have documents that match doc.active='t'.
I also tried it with SIZE(u.documents) which also just returns two users and additionally wrong document-count values.
What is wrong here?
Thanks in advance!
finally after spending hours with that simple stuff, the right solution came with:
SELECT DISTINCT
NEW user.entity.User(u.id,count(doc)) FROM User u
LEFT JOIN u.documents doc ON doc.user = u AND doc.active = 't'
GROUP BY u.id
i have to count the left joined documents itself not the users.
I'm creating a forum and I have recently implemented Simple Membership. What I'm trying to do now is display the actual name of who wrote the post. As of now I'm only able to display the UserId of the user.
I have two models: The Simplemembership model AccountModels, and my ForumModels.
My Forummodel Posts contains a field for UserId.
I've tried adding some of the tables from AccountModels to my ForumModels, but this just caused an error (Since I was trying to create the same table twice)
I've tried creating a ViewModel that contained Posts and UserProfile, but couldn't populate it correctly with data.
Lastly I tried performing a join on the two tables Post and Userprofile
var posts = (from p in db.Posts
join u in udb.UserProfiles
on p.UserId equals u.UserId
where p.TopicId == id
select p);
return View(posts);
This created the error:
The specified LINQ expression contains references to queries that are associated with different contexts.
Any ideas on what I should do?
It seems you're trying to perform a Join between two different contexts. You can either try to:
1) Make a call to the first context and persist the ID collection on a list like this:
var userIds = udb.UserProfiles.UserId.ToList();
var posts = from p in db.Posts
where p.TopicId == id && userIds.Contains(p.UserId)
select p;
2) Add the Posts to the same context as the one used by simple membership and you'll be able to use the join.
Update to Example code
//This will retrieve the posts from the database.
//ToList() will translate and execute the SQL statement,
//so you can manipulate the colleciton in memory
var posts = (from p in db.Posts
where p.TopicId == id
select p).ToList();
//Get all the user IDs on the post collection.
var userIds = posts.Select(p => p.UserId).Distinct();
//Then we will select the users in the posts
var users = ubd.UserProfiles.Where(u => userIds.Contains(u.UserId)).ToList();
//Now you have both collections in memory and you can perform the join
var joined = from p in posts
join u in users
on p.UserId equals u.UserId
select new {Title = p.Title, UserName = u.UserName};