I'm using laravel 8, and I make a query builder to make a left join, when laravel execute the query show me a error, but in SQL Server MS execute correctly
SQLSTATE[42S22]: [Microsoft][ODBC Driver 17 for SQL Server][SQL
Server]Invalid column name '2'. (SQL: select [a].[id] as [id1],
[b].[id] as [id2], [a].[reg], [a].[parte], [a].[ubiclinea],
[a].[descripcion], [a].[numConteo] as [conteo1], [a].[cantidad] as
[cantidad1], [a].[counter] as [contador1], [a].[created_at] as
[created1], [b].[numConteo] as [conteo2], [b].[cantidad] as
[cantidad2], [b].[counter] as [contador2], [b].[created_at] as
[created2] from [directosCount] as [a] left join [directosCount] as
[b] on [a].[reg] = [b].[reg] and [b].[numConteo] = [2] and
[b].[deleted_at] is null where [a].[numConteo] = 1 and
[a].[deleted_at] is null)
that is the error that show
but I copy the query and execute in SQL Server and it works
my query in laravel is this
DB::table('directosCount as a')
->leftJoin('directosCount as b', function($join)
{
$join->on('a.reg', '=', 'b.reg');
$join->on('b.numConteo', '=', '2')->whereNull('b.deleted_at');
})
->select('a.id as id1', 'b.id as id2', 'a.reg', 'a.parte', 'a.ubiclinea', 'a.descripcion', 'a.numConteo as conteo1', 'a.cantidad as cantidad1', 'a.counter as contador1', 'a.created_at as created1', 'b.numConteo as conteo2', 'b.cantidad as cantidad2', 'b.counter as contador2', 'b.created_at as created2')
->where('a.numConteo', '1')
->whereNull('a.deleted_at')
->get();
hope someone can help me
i think this should be outside of join
$join->on('b.numConteo', '=', '2')->whereNull('b.deleted_at');
please change on to where
->where('b.numConteo', '=', '2')->whereNull('b.deleted_at');
You have 2 on statements in your join. Try this
DB::table('directosCount as a')
->leftJoin('directosCount as b', function($join)
{
$join->on('a.reg', '=', 'b.reg')
->where('b.numConteo', '=', '2')
->whereNull('b.deleted_at');
})
->select('a.id as id1', 'b.id as id2', 'a.reg', 'a.parte', 'a.ubiclinea', 'a.descripcion', 'a.numConteo as conteo1', 'a.cantidad as cantidad1', 'a.counter as contador1', 'a.created_at as created1', 'b.numConteo as conteo2', 'b.cantidad as cantidad2', 'b.counter as contador2', 'b.created_at as created2')
->where('a.numConteo', '1')
->whereNull('a.deleted_at')
->get();
Related
when i apply join server show me error
(2/2) QueryException
SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use
my controller
$player_bet = DB::table('player_bet')
->join('poll', 'player_bet.poll_id = poll.id')
->join('poll_type', 'poll_type.id = poll.poll_type_id')
->join('tournament_week', 'poll.week_id = tournament_week.id')
->join('tournament', 'poll.tournament_id = tournament.id')
->join('users', 'player_bet.users_id = users.id')
->join('poll_winner', 'poll_winner.poll_id = poll.id AND poll_winner.user_id = users.id', 'left')
->where('users.id ='.$user_id)
->select('poll_winner.id AS winner_id, poll_winner.winning_amount AS won_amount,, poll_winner.tax_amount AS won_tax_amount, player_bet.id as bet_id, player_bet.create_time,poll.id poll_id,poll.winning_amount,poll.amount poll_amount,poll.week_id week_id,poll.description,poll.description_detail,poll_type.name poll_type,poll_type.id poll_type_id,tournament_week.week_no week_no, poll.is_close is_close, tournament.id tournament_id, tournament.name tournament_name,tournament.start_date,tournament.end_date,tournament.logo, users.username username')
->where('users_id',$user_id)
->get();
Your join syntax is incorrect: https://laravel.com/docs/7.x/queries#joins
Also Your Where condition is Not proper
Problem 1:
Change the multiple condition join method
->join('poll_winner', 'poll_winner.poll_id = poll.id AND poll_winner.user_id = users.id', 'left')
to
->leftjoin('poll_winner', function($join) {
$join->on('poll_winner.poll_id', '=', 'poll.id')
->whereColumn('poll_winner.user_id', 'users.id');
})
Problem 2:
you have two where condition, the where need to be like this, the one is the column, the other be the column's value:
->where('users.id', $user_id)
Problem 3:
If you want to use one string as parameter of select method, you need to use selecRaw
->selectRaw('poll_winner.id AS winner_id, poll_winner.winning_amount AS won_amount,, poll_winner.tax_amount AS won_tax_amount, player_bet.id as bet_id, ...')
Or you need to use multiple strings as parameters of select method:
->select('poll_winner.id AS winner_id', 'poll_winner.winning_amount AS won_amount', ...)
I have a question about query builder.
I wanna made a query that will have conection with two databases
I will show you the SQL query :
SELECT
naviones_db16.ps_orders.payment,
naviones_db16.ps_orders.total_paid AS total,
naviones_db16.ps_orders.current_state AS current_state,
naviones_db16.ps_orders.id_order AS id_order,
naviones_db16.ps_shop.NAME AS name_shop,
naviones_db16.ps_customer.firstname AS customer_firstname,
naviones_db16.ps_customer.lastname AS customer_lastname,
naviones_db16.ps_orders.reference,
naviones_db16.ps_orders.date_add AS fecha
FROM
ps_orders
INNER JOIN naviones_db16.ps_customer ON
naviones_db16.ps_customer.id_customer=
naviones_db16.ps_orders.id_customer
INNER JOIN naviones_db16.ps_shop ON naviones_db16.ps_shop.id_shop =
naviones_db16.ps_orders.id_shop
WHERE
naviones_db16.ps_orders.current_state = 16
AND
naviones_db16.ps_orders.id_order NOT IN (
SELECT
multimarket.productos.id_order
FROM
multimarket.productos
WHERE
multimarket.productos.id_order = naviones_db16.ps_orders.id_order
)
ORDER BY
naviones_db16.ps_orders.id_order DESC
This is that i have done in query builder
$naviones = DB::connection('naviones')->table('ps_orders')
->select('ps_orders.payment', 'ps_orders.total_paid AS total', 'ps_orders.current_state AS current_state', 'ps_orders.id_order AS id_order',
'ps_shop.NAME AS name_shop', 'ps_customer.firstname AS customer_firstname', 'ps_customer.lastname AS customer_lastname', 'ps_orders.reference',
'ps_orders.date_add AS fecha')
->join('ps_customer', 'ps_customer.id_customer', '=', 'ps_orders.id_customer')
->join('ps_shop', 'ps_shop.id_shop', '=', 'ps_orders.id_shop')
->where('ps_orders.current_state', '=', '16')
->orderBy('id_order', 'DESC')
->get()->toArray();
Of course, i have other conection this is: DB::connections('multimarket') but this point i dont have any idea how i could do that. Do you have any idea?
Thank u
Here is my code:
function get_late_jobs($date1, $date2) {
$this->db->select('Delivery.Packlist, Delivery.Job, Delivery.Promised_Date, Delivery.Shipped_Date, Job.Customer');
$this->db->join('Job', 'Delivery.Job = Job.Job', 'inner');
$this->db->where('Delivery.Promised_Date <', 'Delivery.Shipped_Date');
$this->db->where('Delivery.Job IS NOT NULL', NULL);
$this->db->where('Delivery.Shipped_Date IS NOT NULL', NULL);
$this->db->where('Delivery.Shipped_Date >=', $date1);
$this->db->where('Delivery.Shipped_Date <=', $date2);
$this->db->order_by('Delivery.Shipped_Date');
$query = $this->db->get( 'Delivery' );
return $query->result_array();
}
I keep getting this error:
Error Number: 22007/241
[Microsoft][ODBC Driver 13 for SQL Server][SQL Server]Conversion failed when converting date and/or time from character string.
SELECT
"Delivery"."Packlist",
"Delivery"."Job",
"Delivery"."Promised_Date",
"Delivery"."Shipped_Date",
"Job"."Customer"
FROM "Delivery"
INNER JOIN "Job"
ON "Delivery"."Job" = "Job"."Job"
WHERE
"Delivery"."Promised_Date" < 'Delivery.Shipped_Date'
AND "Delivery"."Job" IS NOT NULL
AND "Delivery"."Shipped_Date" IS NOT NULL
AND "Delivery"."Shipped_Date" >= '2018-08-08'
AND "Delivery"."Shipped_Date" <= '2018-08-15'
ORDER BY
"Delivery"."Shipped_Date"
Filename: C:/inetpub/wwwroot/portalci/system/database/DB_driver.php
Line Number: 691
I have already tested the query in SQL Management Studio and the query is an exact copy from an old procedural php page that exist.
I'd suggest replacing
'Delivery.Shipped_Date'
with
"Delivery"."Shipped_Date"
The former is a string constant which cannot be converted to a date.
I am using repository for querying day from date.
if i use only db raw then it works fine, but i don't like to use whole db::raw query in repository so i used db:raw where i needed.
when i used it, it shows error like table not found as table is found if that qyery is removed.
<?php
namespace App\Repositories\Api\Order;
use DB;
use Bosnadev\Repositories\Contracts\RepositoryInterface;
use Bosnadev\Repositories\Eloquent\Repository;
/**
* Class ArticleRepository
*
* #package app\Repository
*/
/**
* Created by PhpStorm.
* User: sabin
* Date: 5/10/16
* Time: 10:29 AM
*/
class OrderRepository extends Repository
{
/**
* #return string
*/
function model()
{
return 'App\Models\Order\Order';
}
function getAll($id)
{
return $this->makeModel()
->join('tbl_sales as sales', 'sales.id', '=', 'tbl_order.sales_id')
->select('sales.date', 'sales.delivery_date', 'sales.total_amount', DB::select(DB::raw("select day(tbl_sales.delivery_date) as day")))
->where('sales.client_id', '=', $id)
->groupBy('tbl_order.sales_id')
->get();
}
}
Error:
SQLSTATE[42S02]: Base table or view not found: 1109 Unknown table 'tbl_sales' in field list (SQL: select day(tbl_sales.delivery_date) as day)
s same problem.
note: i have used sales.delivery_date too, but it show
I have tried putting table command too like:
function getAll($id)
{
return $this->makeModel()
->join('tbl_sales as sales', 'sales.id', '=', 'tbl_order.sales_id')
->select('sales.date', 'sales.delivery_date', 'sales.total_amount', DB::select(DB::raw("select month(tbl_sales.delivery_date) as month from tbl_sales")))
->where('sales.client_id', '=', $id)
->groupBy('tbl_order.sales_id')
->get();
}
but also it is showing this problem.
ErrorException in Grammar.php line 58:
strtolower() expects parameter 1 to be string, array given
You create an alias to the tbl_sales as sales here:
->join('tbl_sales as sales', 'sales.id', '=', 'tbl_order.sales_id')
So I am guessing you should refer to it as sales elsewhere, can you try this to see if it helps:
return $this->makeModel()
->join('tbl_sales as sales', 'sales.id', '=', 'tbl_order.sales_id')
->select(
'sales.date',
'sales.delivery_date',
'sales.total_amount',
// sales here not tbl_sales
DB::select(DB::raw("select day(sales.delivery_date) as day"))
)
->where('sales.client_id', '=', $id)
->groupBy('tbl_order.sales_id')
->get();
If it doesn't work then my approach would be to get the raw sql and get the query working via sql firstly.
To get the raw sql eloquent is generating you could try the following on your query then dd()ing it:
$q = $this->makeModel()
->join('tbl_sales as sales', 'sales.id', '=', 'tbl_order.sales_id')
->select(
'sales.date',
'sales.delivery_date',
'sales.total_amount',
// sales here not tbl_sales
DB::select(DB::raw("select day(sales.delivery_date) as day"))
)
->where('sales.client_id', '=', $id)
->groupBy('tbl_order.sales_id')
->toSql();
dd($q);
or:
DB::enableQueryLog();
dd(DB::getQueryLog());
or install https://github.com/barryvdh/laravel-debugbar
Once you've got the raw sql of the query you can play around with it in your favourite editor and run it directly on the database until you get the desired results then make the required modifications in elqouent to reflect the correct code.
Hope that helps!
i try to join multiple Tables in one Query.
My Entitie Relations:
Person
Entities\Person:
type: entity
table: person
manyToOne:
address:
targetEntity: Address
joinColumn:
name: idaddress
referencedColumnName: idaddress
manyToMany:
tags:
targetEntity: Tag
joinTable:
name: persons_tags
joinColumns:
person_idperson:
referencedColumnName: idperson
inverseJoinColumns:
tag_idtag:
referencedColumnName: idtag
Tag
Entities\Tag:
type: entity
table: tag
manyToMany:
sms:
targetEntity: Sms
mappedBy: tag
sms
manyToMany:
tag:
targetEntity: Tag
joinTable:
name: sms_tags
joinColumns:
sms_idsms:
referencedColumnName: idsms
inverseJoinColumns:
tag_idtag:
referencedColumnName: idtag
This is a valid working SQL Statement:
SELECT DISTINCT person.lastname, person.firstname, address.mobileprivate, address.mobilebusiness FROM
`address`,
`person`,
`persons_tags`,
`sms_tags`
WHERE
person.idaddress = address.idaddress
AND person.idperson = persons_tags.person_idperson
AND persons_tags.tag_idtag = sms_tags.tag_idtag
AND sms_tags.sms_idsms = (myINPUT)
Now i try to join the needed Entities in DQL to get the same result:
SELECT DISTINCT s, t, p, a
FROM Entities\Sms s
JOIN s.sms_idsms t
JOIN t.person_idperson p
JOIN p.idaddress a
WHERE s.idsms = (myINPUT)
But i only get an error:
PHP Fatal error: Uncaught exception 'Doctrine\\ORM\\Query\\QueryException' with message '
SELECT DISTINCT s, t, p, a
FROM Entities\\Sms s
JOIN s.sms_idsms t
JOIN t.person_idperson p
JOIN p.idaddress a
WHERE s.idsms = 2' in
/var/www/ci_doc_rem/Codeigniter_Doctrine/source/application/libraries/Doctrine/ORM/Query/QueryException.php:39
Stack trace:
#0 /var/www/ci_doc_rem/Codeigniter_Doctrine/source/application/libraries/Doctrine/ORM/Query/Parser.php(429): Doctrine\\ORM\\Query\\QueryException::dqlError('SELECT DISTINCT...')
#1 /var/www/ci_doc_rem/Codeigniter_Doctrine/source/application/libraries/Doctrine/ORM/Query/Parser.php(925): Doctrine\\ORM\\Query\\Parser->semanticalError('Class Entities\\...')
#2 /var/www/ci_doc_rem/Codeigniter_Doctrine/source/application/libraries/Doctrine/ORM/Query/Parser.php(1561): Doctrine\\ORM\\Query\\Parser->JoinAssociationPathExpression()
#3 /var/www/ci_doc_rem/Codeigniter_Doctrine/source/application/libraries/Doctrine/ORM/Query/Parser.php(1506): Doctrine\\ORM\\Query\\Parser->JoinAssociationDeclaration()
#4 /var/www/ci_ in /var/www/ci_doc_rem/Codeigniter_Doctrine/source/application/libraries/Doctrine/ORM/Query/QueryException.php on line 49
How to write a DQL Query like the working SQL Query?
I try to avoid a native SQL Query
Here is a try with the Query Builder:
$qb->select(array('s', 't', 'p', 'a'))
->from('Entities\Sms', 's')
->leftJoin('s.tag', 't')
->leftJoin('t.person', 'p')
->leftJoin('p.address', 'a')
->where('s.idsms = 1');
And the Error Message
PHP Fatal error: Uncaught exception 'Doctrine\\ORM\\Query\\QueryException' with message 'SELECT s, t, p, a FROM Entities\\Sms s LEFT JOIN s.tag t LEFT JOIN t.person p LEFT JOIN p.address a WHERE s.idsms = 1' in /var/www/ci_doc_rem/Codeigniter_Doctrine/source/application/libraries/Doctrine/ORM/Query/QueryException.php:39\nStack trace:\n#0 /var/www/ci_doc_rem/Codeigniter_Doctrine/source/application/libraries/Doctrine/ORM/Query/Parser.php(429): Doctrine\\ORM\\Query\\QueryException::dqlError('SELECT s, t, p,...')\n#1 /var/www/ci_doc_rem/Codeigniter_Doctrine/source/application/libraries/Doctrine/ORM/Query/Parser.php(925): Doctrine\\ORM\\Query\\Parser->semanticalError('Class Entities\\...')\n#2 /var/www/ci_doc_rem/Codeigniter_Doctrine/source/application/libraries/Doctrine/ORM/Query/Parser.php(1561): Doctrine\\ORM\\Query\\Parser->JoinAssociationPathExpression()\n#3 /var/www/ci_doc_rem/Codeigniter_Doctrine/source/application/libraries/Doctrine/ORM/Query/Parser.php(1506): Doctrine\\ORM\\Query\\Parser->JoinAssociationDeclaration()\n#4 /var/www/ci_doc_rem/Cod in /var/www/ci_doc_rem/Codeigniter_Doctrine/source/application/libraries/Doctrine/ORM/Query/QueryException.php on line 49
The Solution was to easy to find.
I've replaced the idname namingconvention just by 'id' for every table / entitie and had a closer look to Picking Owning and Inverse Side.
http://docs.doctrine-project.org/en/latest/reference/association-mapping.html#picking-owning-and-inverse-side
This enabled me to write correct Relations.
A big Problem for me, was to decode the Debug Stack Trace to find my error.
Thanks to anyone who spend time to solve my Problem!