How to find a random user with relations in laravel eloquent - eloquent

I have the following query where I am generating a random user.
User::inRandomOrder()
->where('role', 'lender')
->whereNotIn('id', $this->lender_ids)
->where('verified', 'verified')
->first();
Now, I want to add another where condition to check if the user has at least one transaction. The problem here is that transactions are in another table and I do have a one-to-many relation with users and transactions where each user can have multiple transactions but a transaction can belong to only one user.
Now, I want to add a where condition to ensure that this random user must have at least one transaction. So how do I do that?

I think has will solve your problem, it checks the existence of relationship, try this:
User::inRandomOrder()
->where('role', 'lender')
->whereNotIn('id', $this->lender_ids)
->where('verified', 'verified')
->has('transactions')
->first();
Source: https://laravel.com/docs/8.x/eloquent-relationships#querying-relationship-existence

Related

Nest TypeORM Postgres update user's column('number of posts') based on the userId in the Posts Table

I'm wondering if it's possible to auto update the User's column('number of posts') if the Posts table updates. The Post entity has a ManyToOne relation with User('userId'). Is there a way to make the User Table "listen" to the Post Table and automatically updates the number of post column, or i need to write it in the post service create function to do so. I'm new to sql so i'm just trying new stuff. I'm using NestJS,typeORM, Postgres and Graphql
#Kendle's answer does work and has the advantage of pushing the computation and complexity down onto your DB server. Alternatively, you can keep that logic in the application by leveraging TypeORM's Subscribers functionality. Documentation can be found here.
In your specific use case, you could register a subscriber for your Post entity implementing afterInsert and afterRemove (or afterSoftRemove if you soft delete posts) to increment and the decrement the counter respectively.
You don't want to duplicate that data. That's the whole idea of a relational database that different data is kept in different tables.
You can create a view if you want to avoid typing a query with a JOIN each time.
For example you might create the view below:
CREATE VIEW userPosts AS
SELECT
user.id,
user.name,
COUNT(posts.id)
FROM users
LEFT JOIN posts ON user.id = posts.user_id
ORDER BY user.id;
Once you have created the view your can query it as if it were a table.
SELECT * FROM userDate WHERE id = '0001';
Of course I don't have your table definitions and data so you will need to adapt this code to your tables.

How to query a parent table and inherited child table together in one query

I am using go and pq to interface with my postgres database.
I have a simple user table which has basic fields. Id, name, type. My auxillary table, admin inherits from user and adds it's own field panel, and another one that is owner and adds owner. Whether that be using table inheritance, or a supporting table.
My question is if I hit and endpoint that points to user/1 at this point I don't know what type of user this person is yet here. I know we can use jwts and other ways to provide this from the front end. I'm more curious about if there is a way to figure out the user and it's type and query the additional fields in one query?
Ie. I hit the endpoint I would Select from users, get the type, then use that type to get the additional fields. So I would effectively be doing two queries on two tables to get the complete data. Is there a better solution of doing this? Is there some optimizations I could do.

Spring data and MongoDB - bidirectional connection of documents

I have two Documents in my Spring data - MongoDB application:
The first one is Contact and looks like this:
public class Contact {
...
private List<Account> accounts;
and the second one is Account and looks like this:
public class Account {
...
private Contact contact;
My question now is, whether there is a better way of:
1. create contact object
2. save contact object into database
3. create account object
4. set contact object into account object
5. save account object into database
6. set created account object into contact object
7. update contact object
These are many steps and I will avoid to do such a long list to get Contact and Account connected bidirectional.
Try this approach
MongoDB is a NOSQL DB and hence there is no need of an order to be preserved, such as create and store contact object and then do so more in a sequential way.
Maintain a sequence for Contact and Account object. Before storing these two records get the next number in the sequence and insert the Contact and Account documents.
References for autoincrement sequence
https://docs.mongodb.com/v3.0/tutorial/create-an-auto-incrementing-field/
https://www.tutorialspoint.com/mongodb/mongodb_autoincrement_sequence.htm
Pseudo Code:
Get the next Sequence of Contact and Account Id
Add the id's to respective documents
Insert the Documents in Mongodb
While retrieving the records you can use $lookup which is a left outer join.
Please note that chance of loss of integrity in data can happen if one insert is happened successfully and other insert did not happen for some reason.
We dont have transaction support in Mongodb across collections, more info.

JPA fetching too many entries

I have a Customer Entity with a OneToMany relationship to an Invoice Entity.
In plain old sql i can do "select customer_name,customer_age,[some other fields] from customer, invoice where ... [put some filtering here]", which gets me exactly one record with the fields i need.
In JPA i use "select c from Customer c join c.invoiceCollection where ... [same filtering as above]"
This works, but i get the Customer entity with all its associated invoices.
This is nonsense, because i pull a huge amount of (invoices) data from the database, which i do not need. I need only my customer data with exactly one invoice, as specified in the where clause.
To make things worse, i have to loop over the Customer.invoiceCollection in order to find the one specific invoice needed. This costs me even more time plus it exposes my "where" clause to the middle-tier.
Question: is there a JPA select syntax which fetches exactly one record from a one-to-many relationship, as defined in the where clause?
Things tried so far:
a) lazy loading. This does not work, throws an exception whenever i try to access Customer.invoiceCollection.
Even if it worked, i'd get a Collection with some 1000 entries, which i do not need.
b) changed my jpa statement to "select c,i from Customer c join c.invoiceCollection i where ...". This returns me an array of objects, which i have to manually map to a Customer / Invoice entity.
It works, but it makes the ORM philosophy obsolete. If i perform all the mapping from relational database records/fields to java objects manually in my code, why do i need JPA?
This is one of the most infuriating things about JPA. For example, you NEED the OneToMany side if you want Customer to cascade delete Invoices. In most cases you'd like to tell Invoices to delete itself when a Customer is deleted so that Customer does not necessarily need to know about Invoice.
My suggestion for you is that you keep the OneToMany there but get the Lazy Loading working. In your code, do not access "Customer#getInvoices" directly (unless you really need all of them).
This will allow you to do queries on customers that join to invoices without loading them.
I'm guess the exception you are getting just has to do with transaction boundaries which can be easily fixed.
For a lot of these relationships I often add the OneToMany as a private instance variable but I don't create the #getter method. That way I can use it in queries, setup cascade delete, etc. but I don't provide a way to accidentally load thousands of invoices from a customer.
Oh, and for those queries where you need exactly one invoice with its associated customer you should just do the JPA query on the Invoice and then call #getCustomer on that invoice object. That will be eagerly fetched for you.
If you need exactly one invoice with the related customer, why don't you create a query simply based on Invoice?
select i from Invoice i where [same filtering..]
You should not use one-to-many relationship in this case.
One-to-many relationships are suitable for situations when objects at "many" side are logical parts of object at "one" side (e.g. relationship from Invoice to InvoiceLine).
In you case you need a unidirectional many-to-one relationship from Invoice to Customer, so that you can query it as follows:
select i from Invoice i where ...
Then you can use customer field of Invoice to access Customer or filter by its properties.

Many to many relationship with ADO.NET Entity Data Model

I've created many-to-many relationship with ADO.NET with extra order fields in the middle table.
So I have...
Customers
-customer_id
-customer_name
Orders
-order_id
Customers_to_Orders
-customer_id
-order_id
-seq
And now I don't really know how to add new orders to customers with specyfing order, any suggestions?
Create the order first.
Get the ID back for the order.
Then, create the link from the customer to the order.
you add the order to orders table first, and then add it to customer_to_orders preferably in one transaction.
if you're worried about the seq - it can be either identity or you can calculate "next seq" by querying customers_to_orders before adding new data.