How to access model hasMany Relation with where condition in lighthouse graphql? - laravel

I have a model Media with a type column. I want to get files by type with a dynamic where condition.
Model
public function images () {
return $this->hasMany(Media::class, 'recipe_id');
}
public function collection($type) {
return $this->images()->where('collection', '=', $type);
}
Schema.graphql
type User {
id: ID!
title: String!
images: [Media] #hasMany
}
type Media {
id: ID!
collection: String!
name: String!
file: String!
mime_type: String!
user: User #belongsTo
}
The media relationship will give all the images related to this user but I want to access the collection method inside the model.

That should make a trick, and you do not need collection in your Model
Schema.graphql
type User {
id: ID!
title: String!
images (type: String #eq): [Media] #hasMany
}
type Media {
id: ID!
type: String
name: String!
file: String!
mime_type: String!
user: User #belongsTo
}
Or you can do that simply by custom Query but solutions above seams to be more elegant

Related

How to resolve Inconsistent __typename error in Relay?

I just tried to implement the Relay in Frontend for this graphql tutorial, In that tutorial, they created graphql server to store URL(Link) bookmarks with the User who posted those URLs.
The relationship between the link and the users is:
Link belongs_to :user,
User has_many :links.
And I listed out all the Links with Users in Frontend, at the time I got the below error.
Warning: RelayResponseNormalizer: Invalid record 1. Expected __typename to be consistent, but the record was assigned conflicting types Link and User. The GraphQL server likely violated the globally unique id requirement by returning the same id for different objects
I'm not aware of how much it will impact the application. because I got the expected result from Frontend.
Frontend View of Query.
I read this relay official blog for this kind of error, but there is no example to know how exactly to resolve this. so can someone help to resolve this?
Relay Query
graphql`
query LinkListQuery {
allLinks {
id,
description,
url,
postedBy {
id,
name
}
}
}`
Schema:
input AUTH_PROVIDER_CREDENTIALS {
email: String!
password: String!
}
input AuthProviderSignupData {
credentials: AUTH_PROVIDER_CREDENTIALS
}
type Link implements Node {
description: String!
id: ID!
postedBy: User
url: String!
votes: [Vote!]!
}
input LinkFilter {
OR: [LinkFilter!]
descriptionContains: String
urlContains: String
}
type Mutation {
createLink(description: String!, url: String!): Link!
createUser(name: String!, authProvider: AuthProviderSignupData): User!
createVote(linkId: ID): Vote!
signinUser(credentials: AUTH_PROVIDER_CREDENTIALS): SignInUserPayload
}
"""An object with an ID."""
interface Node {
"""ID of the object."""
id: ID!
}
type Query {
allLinks(filter: LinkFilter, first: Int, skip: Int): [Link]!
"""Fetches an object given its ID."""
node(
"""ID of the object."""
id: ID!
): Node
}
"""Autogenerated return type of SignInUser"""
type SignInUserPayload {
token: String
user: User
}
type User implements Node {
email: String!
id: ID!
links: [Link!]!
name: String!
votes: [Vote!]!
}
type Vote {
id: ID!
link: Link!
user: User!
}

GraphQL - Model(s) belong to specific user field

I'm using Lighthouse package to implement GraphQL, the users in my app belong to an entity and I need to get models that belong to the entity of each user, my schema is like this for the moment
"A date string with format `Y-m-d`, e.g. `2011-05-23`."
scalar Date #scalar(class: "Nuwave\\Lighthouse\\Schema\\Types\\Scalars\\Date")
"A datetime string with format `Y-m-d H:i:s`, e.g. `2018-05-23 13:43:32`."
scalar DateTime #scalar(class: "Nuwave\\Lighthouse\\Schema\\Types\\Scalars\\DateTime")
type Query {
me: User #auth
execution: [RobotTime!]! #all
}
type RobotTime {
id: ID!
instance: Instance!
robot: Robot!
start: DateTime!
end: DateTime!
}
type Instance {
id: ID!
name: String!
token: String!
}
type Robot {
id: ID!
start_bot: String!
process: Process!
}
type Process {
id: ID!
name: String!
token: String!
}
type User {
id: ID!
name: String!
email: String!
created_at: String!
updated_at: String
}
I have searched the documentation, but I can't find anything that helps me to do what I need to do.
Currently I have it done in a controller and I return it as a json with a not so complex logic, there are about 5 models that I use.
Sorry for my bad English
You need to declare the appropriate relation in your User model in laravel, sth like this:
public function entity(): BelongsTo
{
return $this->belongsTo(Entity::class);
}
Then add the relation in User type in graphql:
type User {
id: ID!
name: String!
email: String!
created_at: DateTime!
updated_at: DateTime
entity: Entity #belongsTo
}
Of course, you'll need to declare an Entity model in laravel and type in graphql.

GraphQL Prisma - use orderBy on nested relationships

I am fairly new to GraphQL Prisma combo, I cannot seem to order nested relationships without error because the only available orderBy fields are regarding the ID.
My intended goal in the playground would be to create a query that looks similar to the following:
getPosts{
connections(orderBy: "text_asc"){
id
text
}
}
Resolver
getPosts(parent, args, ctx, info){
return ctx.db.query.posts({}, info)
}
Data Model
type Post {
id: ID! #id
isPublished: Boolean! #default(value: false)
title: String!
text: String!
connections: [Connection!]! #relation(name: "ClientConnect")
}
type Link {
id: ID! #id
text: String!
url: String!
}
type Connection {
id: ID! #unique #id
client: Link #relation(name: "LinkConnect")
}

How to resolve subselections / relations in prisma (nested lists)

Let's take an example from the github repo of prisma:
We have a user, the user could have multiple posts, and one post could have multiple links.
My goal is, to retrieve all posts and all links.
This means, my response is a list (links) in a list (posts).
I want to map the values I get back as two nested lists.
datamodel.prisma
type User {
id: ID! #id
email: String! #unique
name: String
posts: [Post]!
}
type Post {
id: ID! #id
createdAt: DateTime! #createdAt
updatedAt: DateTime! #updatedAt
published: Boolean! #default(value: false)
title: String!
content: String
author: User!
links: [Link]!
}
type Link {
id: ID! #id
url: String
title: String
post: Post!
}
schema.graphql
type Query {
...
}
type Mutation {
...
}
type Link {
id: ID!
url: String
title: String
post: Post!
}
type Post {
id: ID!
createdAt: DateTime!
updatedAt: DateTime!
published: Boolean!
title: String!
content: String
author: User!
}
type User {
id: ID!
email: String!
name: String
posts: [Post]!
}
I want to query all posts of a user, and all of the links for every post in the response.
How would I query this request?
user {
id
posts {
id
links {
id
}
}
}
The above code snipper would not work.
EDIT
I want to use the following:
User: {
listPosts: (parent, args, context, info) {
return context.prisma.posts().links()
}
}
So in my response (data in front-end via react-apollo Query Component), I want to map over posts AND the links in each post.
BUT the links attribute in posts is null.
Is there another way to achieve this?!
According to the docs:
Prisma client has a fluent API to query relations in your database. Meaning you can simply chain your method calls to navigate the relation properties of the returned records. This is only possible when retrieving single records, not for lists. Meaning you can not query relation fields of records that are returned in a list.
In order to get around that limitation, you can use the $fragment method:
const fragment = `
fragment UserWithPostsAndLinks on User {
id
email
name
posts {
id
title
content
links {
id
url
title
}
}
}
`
const userWithPostsAndLinks = await prisma.user({ id: args.id }).$fragment(fragment)

authenticate user and serve only their related data

I have a schema in graphcool with these nodes (not sure what the correct term is here... leaf? node? model? type??)
type User #model {
auth0UserId: String #isUnique
createdAt: DateTime!
id: ID! #isUnique
userIdentifier: String
bundleIdentifier: String
updatedAt: DateTime!
devices: [Device!]! #relation(name: "UserOnDevice")
tokens: [Token!]! #relation(name: "TokenOnUser")
}
type Device #model {
id: ID! #isUnique
deviceIdentifier: String!
users: [User!]! #relation(name: "UserOnDevice")
token: Token #relation(name: "DeviceOnToken")
}
I'd like to make it so that a user must be authenticated and be related to the device data to be able to query on it. So, for a query like:
query($deviceIdentifier: String!) {
device(deviceIdentifier: $deviceIdentifier) {
id
}
}
This should return null unless they are autthenticated and are a user in the specified relation. I was thinking I needed a permission query like this one:
query ($node_id: ID!, $user_id: ID!) {
SomeDeviceExists(filter: {
id: $node_id,
users: {
id: $user_id
}
})
}
But it turns out that is invalid. How do I do it?
query ($node_id: ID!, $user_id: ID!) {
SomeDeviceExists(filter: {
id: $node_id,
users_some: {
id: $user_id
}
})
}
but this does require submitting the user_id in the request.

Resources