Laravel query showing different Result in DB::Table and DB::Select with inner join - laravel

I'm using 3 table
1.organizations
2.users
3.organization_user
So the organization_user is the pivot table for getting org. and user.
DB::select("SELECT users.name 'User Name',organizations.name 'Org Name'
FROM users INNER JOIN organization_users ON
organization_users.user_id=users.id
INNER JOIN organizations ON
organizations.id=organization_users.organization_id
WHERE organization_users.organization_id=$org_id");
And getting the below result
[
{
"User Name": "Navid Anjum",
"Org Name": "org1"
},
{
"User Name": "kamal",
"Org Name": "org1"
} ]
But when using
DB::table('organization_users')
->join('users','users.id','=','organization_users.user_id')
->join('organizations','organizations.id','=',
'organization_users.organization_id')
->select('users.name as Name','organizations.name as Org Name')
->where('organization_users.id','=',$org_id)
->get();
And getting the below result
[
{
"Name": "Navid Anjum",
"Org Name": "org1"
} ]
So What I'm doing wrong?

you not set the right id for organization_users in the second statement :
DB::table('organization_users')
->join('users','users.id','=','organization_users.user_id')
->join('organizations','organizations.id','=',
'organization_users.organization_id')
->select('users.name as Name','organizations.name as Org Name')
->where('organization_users.organization_id','=',$org_id)
->get();

Related

Strapi Graphql deep sort

I would like to sort with strapi's graphql
I can do that by
{
users (sort: "id:asc") {
id
username
email
address {
id
city
state
street
}
}
}
I can sort by the first level of columns but how do I go deeper, for example address.city, because
". / :" don't work, graphql playground returns:
"errors": [
{
"message": "select \"users\".* from \"users\" order by \"address\".\"city\" desc limit $1 - missing FROM-clause entry for table \"address\"",

Laravel JOIN DB Raw return hasMany Relathsionship

i have case in my query, i want expect like this
one project hasMany User
total_feedback is calculated from id in feedback table
where the project_id in the feedback table has a relation to the pivot table, namely project_user , i want to calculated how much feedback on a project,
i want expect return JSON like this
"success": 1,
"data": [
{
"id": 1,
"Project_name": "Project Tania Yessi Laksmiwati",
"user_name": {
"User A",
"User B",
"User C",
"User D",
}
"total_feedback": 0
},
{
"id": 2,
"Project_name": "Project Bakijan Bancar Anggriawan",
"user_name": {
"User F",
"User G",
"User C",
}
"total_feedback": 10
},
{
"id": 3,
"Project_name": "Project Mahesa Vega Mahendra",
"user_name": {
"Users A"
},
"total_feedback": 6
},
return JSON above is one project hasMany users
but, now i get return json like this bellow :
"success": 1,
"data": [
{
"id": 1,
"Project_name": "Project Tania Yessi Laksmiwati",
"user_name": "Ilyas Simanjuntak",
"total_feedback": 0
},
{
"id": 2,
"Project_name": "Project Bakijan Bancar Anggriawan",
"user_name": "Ilyas Simanjuntak",
"total_feedback": 0
},
one project return just one users, even though the project with id 1 has 3 users, like project_user table like this bellow
project_id | user_id
1 2
1 4
1 5
this is my query
$user = $this->request->attributes->get('_user');
$query = "SELECT A.id, A.`name` AS Project_name, D.`name` AS user_name, COUNT(C.`id`) AS total_feedback FROM `project` A
JOIN `project_user` B ON A.`id` = B.`project_id` AND B.`user_id` = $user->id
LEFT JOIN `feedback` C ON C.`project_id` = B.`project_id` AND C.`request_id` = B.`user_id`
JOIN `users` D ON D.`id` = B.`user_id`
GROUP BY A.`id`";
$getFeedback = DB::select(DB::raw($query));
but i get project with ID 1 just return one users,, in my case above how to return one project with many users from database, i use the DB query ,, or any suggestion ? Thanks! regards.
If you already have relationships setup, why aren't you using Eloquent for this? You can easily do this with Eloquent with() and withCount() methods. Assuming you have setup your model relationships correctly, you can do something like this instead:
Auth::user()
->projects()
->with(['users', function($query) {
return $query->pluck('name');
}])
->withCount('feedback as total_feedback')
->get();

How can I create a relationship between `json` column and a `int` (id) column in Hasura + Postgres?

I have 2 tables users and post
Table users has columns id and post, column contains an array of the form [1, 2, 3, 4, 5] - where 1, 2, 3, 4, 5 is id in table post
In the table posts the following columns id and text
Table users:
https://i.stack.imgur.com/ywdS7.png
Table posts:
https://i.stack.imgur.com/IBdpb.png
in hasura made an array relation
https://i.stack.imgur.com/311sd.png
Next I made the following request
{
users_test {
postz {
id
}
}
}
I would like to receive such data in response:
postz: [
   {
     text: 'qwe'
   },
   {
     text: 'sdf'
   }
]
But with such a request, I get a trace. error:
{
"errors": [
{
"extensions": {
"internal": {
"statement": "SELECT coalesce(json_agg(\"root\" ), '[]' ) AS \"root\" FROM (SELECT row_to_json((SELECT \"_5_e\" FROM (SELECT \"_4_root.ar.root.postz\".\"postz\" AS \"postz\" ) AS \"_5_e\" ) ) AS \"root\" FROM (SELECT * FROM \"public\".\"users_test\" WHERE ('true') ) AS \"_0_root.base\" LEFT OUTER JOIN LATERAL (SELECT coalesce(json_agg(\"postz\" ), '[]' ) AS \"postz\" FROM (SELECT row_to_json((SELECT \"_2_e\" FROM (SELECT \"_1_root.ar.root.postz.base\".\"id\" AS \"id\" ) AS \"_2_e\" ) ) AS \"postz\" FROM (SELECT * FROM \"public\".\"posts\" WHERE ((\"_0_root.base\".\"post\") = (\"id\")) ) AS \"_1_root.ar.root.postz.base\" ) AS \"_3_root.ar.root.postz\" ) AS \"_4_root.ar.root.postz\" ON ('true') ) AS \"_6_root\" ",
"prepared": true,
"error": {
"exec_status": "FatalError",
"hint": "No operator matches the given name and argument type(s). You might need to add explicit type casts.",
"message": "operator does not exist: json = integer",
"status_code": "42883",
"description": null
},
"arguments": [
"(Oid 114,Just (\"{\\\"x-hasura-role\\\":\\\"admin\\\"}\",Binary))"
]
},
"path": "$",
"code": "unexpected"
},
"message": "postgres query error"
}
]
}
What am I doing wrong and how can I fix it?
A few suggestions:
There are some typos in your query, as far as I can tell. Try:
{
users {
id
posts {
text
}
}
}
You don't need the post column on the users table. You just need a user_id column on the posts table, and a foreign key constraint from the posts table to the users table using the user_id and id columns of the tables respectively. Check out the docs here:
https://docs.hasura.io/1.0/graphql/manual/schema/relationships/create.html#step-3-create-an-array-relationship
https://docs.hasura.io/1.0/graphql/manual/schema/relationships/database-modelling/one-to-many.html
If you have to have the post array column for some reason, you can use computed fields to create a "relationship" between a json array and another table’s id.
https://docs.hasura.io/1.0/graphql/manual/schema/computed-fields.html#table-computed-fields
Your function would:
Take in the json array column
Extract the id's
Return select * from table where id in id's
Example:
https://jsonb-relationships-hasura.herokuapp.com/console/api-explorer
Computed field definition at: https://jsonb-relationships-hasura.herokuapp.com/console/data/schema/public/tables/authors/modify
Run these queries:
# Get list of articles for each author
query {
authors {
id
name
articles
}
}
# Get actual articles for each author
query {
authors {
id
name
owned_articles {
id
title
}
}
}

How to query without using Eloquent?

I have these few tables:
issues
1. id
2. name
tags
1. id
2. name
issue_tag
1. issue_id
2. tag_id
images
1. id
2. url
3. issue_id
The relationship of these tables is stated below:
Issue hasMany Images, Images belongsTo Issue
Issues belongsToMany Tags, Tags belongsToMany Issues
How can I retrieve all the records by NOT USING ELOQUENT, just by using the QUERY BUILDER. I would like to retrieve the data in the format like:
[
{
id: issue_id,
name: issue_name,
tags: [
{
id: tag_id_1,
name: tag_name_1
},
{
id: tag_id_2,
name: tag_name_2
}
]
},
{
...
},
...
]
Please someone help me because I could not solve this problem for a long time, I can only solve it by using Eloquent. But using Eloquent is not a solution for me.
You can use join query. For Details follow this link demo
Or
Use DB:: statement ('your raw query here'). Hope this helps.
Use can Laravel DB::select(); function
With the use of select, we can pass Raw SQL query into select
$innerData = [];
$issueAll = DB::select('select i.id,i.name,i2.url as image,t.id as tag_id,
t.name as tag_name,it.issue_id from issues as i
inner join issue_tag as it on it.issue_id=i.id
inner join tags as t on it.tag_id = t.id
inner join images as i2 on i.id = i2.issue_id
');
foreach ($issueAll as $issue) {
$innerData[$issue->id]["id"] = $issue->id;
$innerData[$issue->id]["name"] = $issue->name;
if (isset($innerData[$issue->id]['tags'][$issue->issue_id])) {
array_push($innerData[$issue->id]['tags'], ['id'=>$issue->tag_id, 'name'=>$issue->tag_name]);
} else {
$innerData[$issue->id]['tags'][$issue->issue_id] = ['id'=>$issue->tag_id, 'name'=>$issue->tag_name];
}
}
return $innerData;
The response you get
{
"1":{
"id":1,
"name":"issue1",
"tags":{
"1":{
"id":1,
"name":"tag1"
},
"2":{
"id":1,
"name":"tag1"
}
}
},
"2":{
"id":2,
"name":"issue2",
"tags":{
"2":{
"id":1,
"name":"tag1"
}
}
}
}
Hope it helps.
In laravel if you don't want to use eloquent then you can use with DB::statement('your query') and don't forget to use USE DB; at the top of the file

how to get id of last inserted row in RDS Aurora in GraphQL mutation

I've a table with (id, price). id is autoincremented. I want to return the id and full data of last inserted row.
Resolver:
{
"version": "2018-05-29",
"statements": [
"insert into notes (price) VALUES (100)",
"select * from notes WHERE id = $id"
]
}
How can I find the id of last inserted row. Second query of course will not work here as id is not known.
Does SELECT LAST_INSERT_ID(); work well in serverless context? How to store that variable and run third query?
I was running into the same issue. So far, this seems to work for us:
{
"version": "2018-05-29",
"statements": [
"INSERT INTO customer_addresses (`id`, `customerid`, `firstname`, `lastname`) VALUES (NULL, :CUSTOMERID, :FIRSTNAME, :LASTNAME)",
"SELECT * FROM customer_addresses WHERE id = LAST_INSERT_ID()"
],
"variableMap": {
":CUSTOMERID": $context.args.customerid,
":FIRSTNAME": "$context.args.input.firstname",
":LASTNAME": "$context.args.input.lastname"
}
}

Resources