Typeorm query for entity using another entity in where clause in version 0.3.X - square

In my system we have users and addresses.
I want to query the addresses table for all the addresses belonging to a user.
Within the version 0.2.X I was able to write the query like
user: UserEntity = blah
AddressEntity.findOne({ user: user }))
Whereas now I need to do
user: UserEntity = blah
AddressEntity.findOneBy({ user: {id : user.id }))
Is there any workaround to support the shorthand notation again?

Related

how we can optimize sql request to db to avoid extra information and decrease the time response in nested models?

We work with SQLalchemy and postgre sql to write api.We have 2 nested models: user and company.
class UserBaseModel(BaseModel):
first_name: str
last_name: str
email: str
company:CompanyModel
class CompanyCreateModel(BaseModel):
name: str
description: Optional[str] = None
def get_all_companies(db: Session, name_like: Optional[str]) -> List[Company]:
query = db.query(Company)
if name_like:
query = query.filter(Company.name.ilike(f"%{name_like}%"))
return query.all()
and with this query.all() in response it gives back whole the class of company inside the user but i only need company_id.
I also want to know if it the pydantic model which triggers the sql requests or it's just a filter on results after sending the request to the database.

Typeorm: Check if a property is either value 1, 2, 3 or n

I want to get all tasks that have a certain role. I have an array of strings for which I want to get the tasks.
Query:
return this.createQueryBuilder('task')
.select(this.baseSelect)
.where('task.role = :role', { role }) // What here?
.getMany();
This code of course only gets the tasks for which the role is that one value.
How can I check multiple values?
For searching in multiple roles you can use the IN operator:
OLD VERSION of TypeORM
return this.createQueryBuilder('task')
.select(this.baseSelect)
.where('task.role IN(:roles)', {roles: [role1, role2, role3]});
.getMany();
NEW VERSION of TypeORM
As mentioned by user Christophe Geers, In the new version, you will have to use the spread syntax.
return this.createQueryBuilder('task')
.select(this.baseSelect)
.where('task.role IN(:...roles)', {roles: [role1, role2, role3]});
.getMany();

Codeception How to test if a User has a Role

I am trying to get into the habit of writing tests as I go.
I am using Laravel 4.2 to build an application that registers Users and assigns different roles to different user types.
I want to write a test that will check to see if a User has a Role. I am using Entrust to manage my Roles/Permissions and Laracasts/TestDummy to generate dummy objects.
The Roles are stored in a pivot table, so I am essentially testing for the existance of a many to many relationship
The TestDummy documentation states that I need to define my objects and their relationships in a fixtures.yml file and gives an example
Post:
title: Hello World $string
body: $text
published_at: $date
author_id:
type: Author
Author:
name: John Doe $integer
The above layout defines a one to one relationship. A post has An Author.
What I am trying to test for is A User has A Role, where many Users can have Many Roles
I want to know how to define this in my fixtures.yml file
in my mind
If I wanted to test a Many to Many Relationship (Many Users have Many Roles) could I reference it like this?
Excel\Users\User:
username: $string$integer
email: $string$integer#example.com
password: $string
created_at: $date
updated_at: $date
\Role:
name: $string
created_at: $date
updated_at: $date
Assigned_Role:
user_id:
type: Excel\Users\User
role_id:
type: \Role
The problem as I see it is that Assigned_Role does not have a model as it is just a pivot table
How could I test if a User has a specific Role?
TestDummy only supports generating belongs to relations. You can try something like this, assuming you want to test a method on User like hasRole($role).
$user = Factory::create('Excel\Users\User');
$role = Factory::create('Role');
$user->roles()->attach($role);
$this->assertTrue($user->hasRole($role));
$user->roles()->detach($role);
$this->assertFalse($user->hasRole($role));

SQL query to filter out users who already have recieved an email

Suppose:
You tried to send a mass mailing, but something went wrong, and only some users got the mail.
You sent a mass mailing recently, but now new users have signed up, and they need to receive the mail as well.
How do you filter those who have already received the news (via an Eloquent query or a select command from database .)
Actually I faced this problem in a project based on Laravel 4, I am searching for a query using Laravel Eloquent on a pivot table and keep track the sent emails to the users.
In my case there is two Model: Post and User
Its a many to many relationship: any user can receive many posts and any post can be sent to many users
You'll want to add a column to your users table eg a datetime field called mailed_at. Then in your email or signup method (wherever it is you're sending that first email) update the user with the datetime they were emailed.
From then on you can query based on mailed_at for any users who still need an email.
To check for multiple users that need a newsletter, let's say your users table schema is as follows (keeping it simple):
id | email | password | mailed_at (nullable)
We check here whether a user has received an email by querying based on the mailed_at column. To get all users that need to receive a mailout you would do the following:
$usersToMail = User::whereNull('mailed_at')->get();
There is two Model: Post and User
Its a many to many relationship: any user can receive many posts and any post can be sent to many users
I implemented it as the following:
class Post extends Eloquent {
public function recipients()
{
return $this->belongsToMany('User', 'posts_users', 'post_id', 'user_id');
}
}
class User extends Eloquent {
public function mails()
{
return $this->belongsToMany('Post', 'posts_users', 'user_id', 'post_id');
}
}
So, when I want to send a post to users I use
$usersToMail = User::whereNotExists(function($query) use ($post_id)
{
$query->select(DB::raw(1))
->from('posts_users')
->whereRaw('posts_users.user_id = users.id')
->whereRaw('posts_users.post_id = '.$post_id);
})->get();
foreach ($usersToMail as $user)
{
// send email
$user->mails()->save($post); // it records that this post has been sent to the user
}

Grails; how to refer to a domain property in native sql query

I have a domain class UserProfile which has one to one relationship with another domain class User.The Structure of the domain is provided.
сlass UserProfile {
String fio
String position
String phone
String email
static belongsTo = [user: User]
static constraints = {
// some constraints
}
static mapping = {
//some mapping; user property is not mapped
}
I need to write a native sql query in Grails for UserProfile domain and I don't know how to refer to user property(static belongsTo = [user: User]). I have tried USER_ID but it is not working.
I can't name the column directly using mapping section; I just need to find out how user column in UserProfile domain is named in database and how it can be called in native sql query.
Very Simple if i got your question ,Grails gorm convention for storing fileds in data base is:
Like
user_profile for UserProfile -Domain
and all fileds are speparedted by underscores and most of the time gorm adds _id after a foreign key reference /or a GORM relationship like above One to One and one to Many
[belongsTo=[user]] .
Inside SQL Table
mysql describe user_profile ;
----------------------------------------------------------------
User_Profile
----------------------------------------------------------------
id
version
foo varchar(50)
postion
email
user_instance_id int
-------------------------------------------------------------------
NATIVE SQL QUERY WILL BE :
'select up.user_instance_id from user_profile as up '
the Get all the userInstance objects by querying the user table
'select * from user where user.id = 'the id you get it from the above query'
I hope you have some idea on this please ,if i didnt get it let me know.
I believe if you define user inside UserProfile, then you can access it and will automatically be mapped? It works in my previous projects, I hope it will work with this.
сlass UserProfile {
String fio
String position
String phone
String email
static belongsTo = [user: User]
User userInstance;
static constraints = {
// some constraints
}
Then you can use it
UserProfile.executeQuery("select up.userInstance from UserProfile up")