Native query to Laravel eloquent - eloquent

Good day, I have 3 tables which is products, users, and pivot product_user table.
and I want to fetch all the data in the main table if that row contains a pivot data.
Example
products table
ID Name
1 sample 1----------> is in pivot table **product_user**
2 sample 2----------> is in pivot table **product_user**
3 sample 3
users table
ID Name
1 user1-------------> is in the pivot table **product_user**
2 user2
3 user3-------------> is in the pivot table **product_user**
product_user
product_id user_id
1 1
3 2
In this scenario how can I fetch the data in the two main table that contains pivot data?
How can I achieve the result of this query in laravel way?
SELECT p.`name`, u.`first_name`
FROM product_user AS pu
LEFT JOIN products AS p
ON pu.`product_id` = p.id
LEFT JOIN `users` AS u
ON pu.`user_id` = u.`id`
result
name first_name
sample 1 user firstname

You have a BelongsToMany relationship Product ↔ User:
class ProductUser extends Model {
public function product() {
return $this->belongsTo(Product::class);
}
public function user() {
return $this->belongsTo(User::class);
}
}
$pivots = ProductUser::with('product', 'user')->get();
foreach($pivots as $pivot) {
// $pivot->user->first_name
// $pivot->product->name
}

Related

How to get value of specific column on first table and insert into the second table in Spring boot JPA

I have a project I want to get data from a specific column from table one and insert those data by id to the specific column in table 2 what query could I use? how to get data from specific column from table 1 to a specific column to table 2
here's my Repository
#Query(value = "SELECT :refId FROM product WHERE id = :id", nativeQuery=true)
public String findReferenceid(#Param(value = "id") long id, #Param(value = "refId") String refId);
Thanks.

SQL join table with a dynamic database name

I have a table which contains a employee ID and a database ID code in database DBX0 table 'FirstTable':
Employee ID
Database ID
123
1
456
2
789
2
149
3
The database name is stored in a different table 'databases' like :
Database ID
DB name
1
DBX1
2
DBX2
3
DBX3
So what I'm trying to do is join the first table with a separate table which is stored in the identified database, like
SELECT * from DBX0.dbo.FirstTable a join (SELECT [DB name] from DBX0.dbo.databases where [database ID] = a.[database ID]).dbo.OtherTable
(I don't think this will actually work with a subquery, but this would return the result that I want in theory.)
I have tried dynamic sql with a cursor to iterate through each database and then only return results based on database ID = database ID and Employee ID = Employee ID, but this returns the results in a separate result per database.
Also tried:
Select * from (SELECT * from DBX0.dbo.FirstTable a join '+#dbname+'.dbo.OtherTable on a.employeeid = b.employeeid and a.dbid = b.dbid)
in dynamic sql, but this didn't work either.
Is there any way to get all of the data in one result?

join and count query in flutter sqflite

I have 2 tables one with names and id's and another with id's and dates,
I am trying to figure out how to create the helper method to query the two tables and return the list of names with the number of dates associated to their id.
Name Table
id Name
1 John
2 Tom
3 Frank
Date Table
id Date
1 1/3/19
1 1/4/19
1 1/5/19
2 1/4/19
Results:
Name Count
John 3
Tom 1
Frank 0
This is as far as I have gotten just pulling back all the names.
Future<List> queryAllNames() async {
Database db = await database;
List<Map> names =
await db.query(Names, columns: [id, Name]);
if (names.length > 0) {
return names;
}
return null;
}
I have figured out the raw query I need from sqlite
select Name.name, count(Date.date) from Name left join Date using(id) group by Name.name;
But still not able to translate to at sqflite helper method.
There is a rawQuery() method. Check out Raw SQL queries

Entity Framework - query inside a where statement

I have a scenario where I need to fetch list of string values from a table.
I need to query the Subject table and get list of subjects:
EmployeeDetails emp = new EmployeeDetails();
emp.subjects = from x in EmpDB.subjects
join y in EmpDB.employeeInfo
on x.subjectCode equals y.subjectCode select new
{
x.subjectTitle,
}.toList();
I have an employee ID which I need to query the EmployeeDetails table and get SubjectCodes of that particular Employee ID, and using those subject codes, I need to query the Subject table and get the subject values.
I assume that in EmployeeDetails class you have property Subjects with List.
EmployeeDetails emp = new EmployeeDetails();
emp.subjects = (from x in EmpDB.subjects
join y in EmpDB.employeeInfo on x.subjectCode equals y.subjectCode
where y.EmployeeId = <<your ID>> // Employee ID you searching
select x.subjectTitle).ToList();

JPA Query over a join table

I have 3 tables like:
A AB B
------------- ------------ ---------------
a1 a1,b1 b1
AB is a transition table between A and B
With this, my classes have no composition within these two classes to each other. But I want to know that , with a JPQL Query, if any records exist for my element from A table in AB table. Just number or a boolean value is what I need.
Because AB is a transition table, there is no model object for it and I want to know if I can do this with a #Query in my Repository object.
the AB table must be modeled in an entity to be queried in JPQL. So you must model this as
an own entity class or an association in your A and or your B entity.
I suggest to use Native query method intead of JPQL (JPA supports Native query too). Let us assume table A is Customer and table B is a Product and AB is a Sale. Here is the query for getting list of products which are ordered by a customer.
entityManager.createNativeQuery("SELECT PRODUCT_ID FROM
SALE WHERE CUSTOMER_ID = 'C_123'");
Actually, the answer to this situation is simpler than you might think. It's a simple matter of using the right tool for the right job. JPA was not designed for implementing complicated SQL queries, that's what SQL is for! So you need a way to get JPA to access a production-level SQL query;
em.createNativeQuery
So in your case what you want to do is access the AB table looking only for the id field. Once you have retrieved your query, take your id field and look up the Java object using the id field. It's a second search true, but trivial by SQL standards.
Let's assume you are looking for an A object based on the number of times a B object references it. Say you are wanting a semi-complicated (but typical) SQL query to group type A objects based on the number of B objects and in descending order. This would be a typical popularity query that you might want to implement as per project requirements.
Your native SQL query would be as such:
select a_id as id from AB group by a_id order by count(*) desc;
Now what you want to do is tell JPA to expect the id list to comeback in a form that that JPA can accept. You need to put together an extra JPA entity. One that will never be used in the normal fashion of JPA. But JPA needs a way to get the queried objects back to you. You would put together an entity for this search query as such;
#Entity
public class IdSearch {
#Id
#Column
Long id;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
}
Now you implement a little bit of code to bring the two technologies together;
#SuppressWarnings("unchecked")
public List<IdSearch> findMostPopularA() {
return em.createNativeQuery("select a_id as id from AB group by a_id
order by count(*) desc", IdSearch.class).getResultList();
}
There, that's all you have to do to get JPA to get your query completed successfully. To get at your A objects you would simply cross reference into your the A list using the traditional JPA approach, as such;
List<IdSearch> list = producer.getMostPopularA();
Iterator<IdSearch> it = list.iterator();
while ( it.hasNext() ) {
IdSearch a = it.next();
A object = em.find(A.class,a.getId());
// your in business!
Still, a little more refinement of the above can simplify things a bit further actually given the many many capabilities of the SQL design structure. A slightly more complicated SQL query will an even more direct JPA interface to your actual data;
#SuppressWarnings("unchecked")
public List<A> findMostPopularA() {
return em.createNativeQuery("select * from A, AB
where A.id = AB.a_id
group by a_id
order by count(*) desc", A.class).getResultList();
}
This removes the need for an interm IdSearch table!
List<A> list = producer.getMostPopularA();
Iterator<A> it = list.iterator();
while ( it.hasNext() ) {
A a = it.next();
// your in business!
What may not be clear tot the naked eye is the wonderfully simplified way JPA allows you to make use of complicated SQL structures inside the JPA interface. Imagine if you an SQL as follows;
SELECT array_agg(players), player_teams
FROM (
SELECT DISTINCT t1.t1player AS players, t1.player_teams
FROM (
SELECT
p.playerid AS t1id,
concat(p.playerid,':', p.playername, ' ') AS t1player,
array_agg(pl.teamid ORDER BY pl.teamid) AS player_teams
FROM player p
LEFT JOIN plays pl ON p.playerid = pl.playerid
GROUP BY p.playerid, p.playername
) t1
INNER JOIN (
SELECT
p.playerid AS t2id,
array_agg(pl.teamid ORDER BY pl.teamid) AS player_teams
FROM player p
LEFT JOIN plays pl ON p.playerid = pl.playerid
GROUP BY p.playerid, p.playername
) t2 ON t1.player_teams=t2.player_teams AND t1.t1id <> t2.t2id
) innerQuery
GROUP BY player_teams
The point is that with createNativeQuery interface, you can still retrieve precisely the data you are looking for and straight into the desired object for easy access by Java.
#SuppressWarnings("unchecked")
public List<A> findMostPopularA() {
return em.createNativeQuery("SELECT array_agg(players), player_teams
FROM (
SELECT DISTINCT t1.t1player AS players, t1.player_teams
FROM (
SELECT
p.playerid AS t1id,
concat(p.playerid,':', p.playername, ' ') AS t1player,
array_agg(pl.teamid ORDER BY pl.teamid) AS player_teams
FROM player p
LEFT JOIN plays pl ON p.playerid = pl.playerid
GROUP BY p.playerid, p.playername
) t1
INNER JOIN (
SELECT
p.playerid AS t2id,
array_agg(pl.teamid ORDER BY pl.teamid) AS player_teams
FROM player p
LEFT JOIN plays pl ON p.playerid = pl.playerid
GROUP BY p.playerid, p.playername
) t2 ON t1.player_teams=t2.player_teams AND t1.t1id <> t2.t2id
) innerQuery
GROUP BY player_teams
", A.class).getResultList();
}