I have the following Eloquent Query in one of my Models:
return self::where('sequence', '=', $sequence)->where('interval', '=', $minutes)
->leftJoin('wallet', 'wallet_stats.wallet_id', '=', 'wallet.id')
->leftJoin('balance', function($join) use ($uid)
{
$join->on('balance.wallet_id', '=', 'wallet_stats.wallet_id')
->on('balance.user_id', '=', $uid);
})
->orderBy('volume', 'ASC')->get(['symbol', 'name', 'volume', 'start_price', 'end_price']);
The problem I'm having with this is the following error message:
Oops! SQLSTATE[42S22]: Column not found: 1054 Unknown column '2' in
'on clause' (SQL: select symbol, name, volume, start_price,
end_price from wallet_stats left join wallet on
wallet_stats.wallet_id = wallet.id left join balance on
balance.wallet_id = wallet_stats.wallet_id and
balance.user_id = 2 where sequence = 0 and interval = 1440
order by volume asc)
For some reason Eloquent insists on using the value of $uid (in the 2nd "on" join condition) as a column name rather than a literal value.
Does anybody know how to get around that and have it accept a literal value in such a join specification?
I can't quite seem to replicate your error however this is what I've used in past instances. Giedrius Kiršys' suggestion in the comment on your question is also good.
return self::where('sequence', '=', $sequence)->where('interval', '=', $minutes)
->leftJoin('wallet', 'wallet_stats.wallet_id', '=', 'wallet.id')
->leftJoin('balance', function($join) use ($uid)
{
$join->on('balance.wallet_id', '=', 'wallet_stats.wallet_id')
->on('balance.user_id', '=', \DB::raw($uid));
})
->orderBy('volume', 'ASC')->get(['symbol', 'name', 'volume', 'start_price', 'end_price']);
This assumes you haven't already imported DB, if you have get rid of the \
Use ->where() for 2nd on clause, such as
->leftJoin('balance', function($join) use ($uid)
{
$join->on('balance.wallet_id', '=', 'wallet_stats.wallet_id');
$join->where('balance.user_id','=', $uid);
})
Or, use the DB::raw() for on clause value
->leftJoin('balance', function($join) use ($uid)
{
$join->on('balance.wallet_id', '=', 'wallet_stats.wallet_id');
$join->on('balance.user_id', '=', DB::raw($uid));
})
Related
Im having a hard time converting this raw MySQL query in phpmyadmin. I want to convert it to laravel's query builder or eloquent. I already configured the relationships in the model. Can someone convert my query to querybuilder and eloquent? I tried some converter but it doesnt work for me. Thanks
Raw Query
SELECT count( * ) FROM users u, sectionschedules s, notes n
WHERE u.parent_id=26
AND u.section_id=s.section_id
AND s.id = n.schedule_id;
Query I tried
$notes = DB::table('notes')
->join('users', 'users.section_id', '=', 'notes.section_id')
->join('sections','sections.section_id', '=', 'sectionschedules.section_id')
->join('sectionschedules', 'sectionschedules.id','=','notes.schedule_id')
->where('user.parent_id', '=', 26)
->count();
Error I got
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'user.parent_id' in 'where clause
Try
$notes = DB::table('sectionschedules')
->select('notes.*','sectionschedules.*','users.*')
->join('users','users.section_id', '=', 'sectionschedules.section_id')
->join('notes', 'sectionschedules.id','=','notes.schedule_id')
->where('users.parent_id', '=', 26)
->count();
$notes = DB::table('notes')
->join('users', 'users.section_id', '=', 'notes.section_id')
->join('sections','sections.section_id', '=', 'sectionschedules.section_id')
->join('sectionschedules', 'sectionschedules.id','=','notes.schedule_id')
->where('users.parent_id', '=', 26)
->count();
Users.parent id as defined not user.parent_id
I have the following raw SQL that I'm trying to convert into Eloquent form:
SELECT oe.eventID, oe.eventName, oet.etName, date_format(oe.eventStartDate, '%c/%d/%Y') as eventStartDate,
date_format(oe.eventEndDate, '%c/%d/%Y') AS eventEndDate
FROM `org-event` oe
JOIN `org-event_types` oet on oe.eventTypeID=oet.etID and oet.orgID=?
JOIN `event-registration` er on er.eventID = oe.eventID
WHERE (er.regStatus='Active' or er.regStatus='In Progress') AND personID=? AND oe.deleted_at is NULL
ORDER BY oe.eventStartDate DESC
I've crafted the following and I'm running into an error saying that '10' isn't a column. 10 is the value of $this->currentPerson->defaultOrgID
DB::table('org-event')
->join('org-event_types', function($join) {
$join->on('org-event_types.etID', '=', 'org-event.eventTypeID');
$join->on('org-event_types.orgID', '=', $this->currentPerson->defaultOrgID);
})->join('event-registration', 'event-registration.eventID', '=', 'org-event.eventID')
->where('event-registration.personID', '=', auth()->user()->id)
->where(function($w) {
$w->where('event-registration.regStatus', '=', 'Active')
->orWhere('event-registration.regStatus', '=', 'In Progress');
})
->select('org-event.eventID', 'eventName', 'etName', 'eventStartDate', 'eventEndDate')
->orderBy('org-event.eventStartDate')->get();
I dropped the deleted_at where clause because that's automatic using eloquent.
You have to join on the corresponding foreign key: oe.eventTypeID=oet.etID and then supply a where explaining what you want to filter your results by, i.e. ->where('orgID','=',$this->currentPerson->defaultOrgID).
DB::table('org-event')
->join('org-event_types', function($join) {
$join->on('org-event_types.etID', '=', 'org-event.eventTypeID');
$join->on('org-event_types.orgID', '=', 'org-event.eventTypeID')->where('orgID','=',$this->currentPerson->defaultOrgID);
})->join('event-registration', 'event-registration.eventID', '=', 'org-event.eventID')
->where('event-registration.personID', '=', auth()->user()->id)
->where(function($w) {
$w->where('event-registration.regStatus', '=', 'Active')
->orWhere('event-registration.regStatus', '=', 'In Progress');
})
->select('org-event.eventID', 'eventName', 'etName', 'eventStartDate', 'eventEndDate')
->orderBy('org-event.eventStartDate')->get();
Here's my situation I have joined tables but the problem is some of those columns have the same name from other tables. What I want to know is how I can prevent this from happening. The columns that have the same name are created_at but I only want to use methods' table created_at (methods.created_at). Here is my code to explain my situation better
$filtered_table = Method::leftJoin('users', 'users.id', '=', 'methods.created_by')
->leftJoin('roles', 'roles.id', '=', 'users.role_id')
->leftJoin('types', 'types.id', '=', 'methods.type_id')
->where($request->filters)//will act as a searchmap
->get([ 'users.username', 'users.id AS users_id', 'methods.*', 'methods.id AS method_id', 'methods.name AS method_name', 'roles.id AS role_id', 'roles.name AS role_name',
'types.id AS type_id_typetable', 'types.name AS type_name']);
notice how ->where is an array of objects, I am using it as a searchmap for the clause. But my problem is like what I said above that the tables has the same name on some columns like for example created_at, the other columns doesn't matter since I am not using it.
The question is how do I explicitly tell the query that I am using the methods.created_at when I am searching it through the searchmap (In this case, $request->filters['created_at']. Please, let me know if you need any more details.
EDIT
if($("#date_select_off").val() == "daily") {
let day = $("#day_date").val();
filter_list.created_at = day;
}
in this code in jquery I am naming the key the same as the column so that I can use it as parameter in the php query. But my like my initial problem I simply can't name it filter_list.methods.created_at any help with this is greatly appreciated.
EDIT 2
How would I use a 'LIKE' query to that particular key value pair?
->where($request->filters)//will act as a searchmap
->orWhere('methods.created_at', 'LIKE', $request->filters['methods.created_at'])
I tried doing this but it is just wrong since the key value pair is already hitting on the first where clause.
EDIT 3
It could use some improvements but yeah
$filtered_table = Method::leftJoin('users', 'users.id', '=', 'methods.created_by')
->leftJoin('roles', 'roles.id', '=', 'users.role_id')
->leftJoin('types', 'types.id', '=', 'methods.type_id')
->where($request->filters)//will act as a searchmap
->orWhere('methods.created_at', 'LIKE', '%' . $request->filters['methods.created_at'] . '%')
->get([ 'users.username', 'users.id AS users_id', 'methods.id AS method_id', 'methods.name AS method_name', 'methods.created_at AS method_created_at', 'roles.id AS role_id', 'roles.name AS role_name',
'types.id AS type_id_typetable', 'types.name AS type_name']);
Change your model class as per your requirements to specify what columns you want selected:
public function someModel() {
return $this->belongs_to('otherModel')->select(array('id', 'name'));
}
In this case pass the fully qualified column name in where clause like:
->where('methods.created_at', '=', $request->filters)
or create a table alias and use the alias like:
SELECT col from methods as t1,
...
WHERE t1.col = 'some value';
I have a question regarding join clauses in Eloquent, and whether you can join on a string value rather than a table column.
I have the code below querying a nested set joining parent/child records in a table 'destinations' via a table 'taxonomy'.
The second $join statement in the closure is the one causing an issue; Eloquent assumes this is a column, when I would actually just like to join on t1.parent_type = 'Destination' - ie, t1.parent_type should = a string value, Destination.
$result = DB::connection()
->table('destinations AS d1')
->select(array('d1.title AS level1', 'd2.title AS level2'))
->leftJoin('taxonomy AS t1', function($join) {
$join->on('t1.parent_id', '=', 'd1.id');
$join->on('t1.parent_type', '=', 'Destination');
})
->leftJoin('destinations AS d2', 'd2.id', '=', 't1.child_id')
->where('d1.slug', '=', $slug)
->get();
Is it possible to force Eloquent to do this? I've tried replacing 'Destination' with DB::raw('Destination') but this does not work either.
Thanking you kindly.
Another best way to achieve same is :
$result = DB::connection()
->table('destinations AS d1')
->select(array('d1.title AS level1', 'd2.title AS level2'))
->leftJoin('taxonomy AS t1', function($join) {
$join->on('t1.parent_id', '=', 'd1.id');
$join->where('t1.parent_type', '=', 'Destination');
})
->leftJoin('destinations AS d2', 'd2.id', '=', 't1.child_id')
->where('d1.slug', '=', $slug)
->get();
Replace your on with where
try using DB::raw("'Destination'")
Right now I want to have the sum of Sueldo in a column grouped by idEmpleado of table recibo. Im not sure if I can put the DB::table inside the left join. if not how could I call that table in a query to make a join with the information of the empleado.
Here is what I have so far
$pagos = DB::table('empleado')
->leftJoin('empresa', 'empresa.idEmpresa', '=', 'empleado.emp_idEmpresa_FK')
->leftJoin('departamento', 'departamento.idDepartamento', '=', 'empleado.emp_idDeparameto_FK')
->leftJoin('tipoperiodo', 'tipoperiodo.idTipoPeriodo', '=', 'empleado.emp_idTipoPeriodo_FK')
->leftJoin(
DB::table('recibos')
->leftJoin('empleado', 'empleado.idEmpleado', '=', 'recibos.rec_idEmpleado_FK')
->select(DB::raw('idRecibos, rec_idEmpleado_FK, SUM(SueldoBase) as Restante'))
->groupBy('rec_idEmpleado_FK')
->get()
,'recibos', 'recibos.rec_idEmpleado_FK', '=', 'empleado.idEmpleado')
->select('idEmpleado', 'Nombre', 'Nombre_Depto', 'Nombre_Empresa', 'Puesto', 'SueldoBase', 'Restante')
->get();
I'm getting an error ErrorException with message :
Array to string conversion
I'm suppose its because I'm trying to make a leftjoin of a query im making there. Dunno Im knid of new to this. Any suggestions ?
With the help of the answer in the commnets I got to this Query,
DB::table('empleado')
->leftJoin('empresa', 'empresa.idEmpresa', '=', 'empleado.emp_idEmpresa_FK')
->leftJoin('departamento', 'departamento.idDepartamento', '=', 'empleado.emp_idDeparameto_FK')
->leftJoin('tipoperiodo', 'tipoperiodo.idTipoPeriodo', '=', 'empleado.emp_idTipoPeriodo_FK')
->leftjoin(
DB::raw('SELECT rec_idEmpleado_FK, SUM( SueldoBase ) AS Restante
FROM `recibos`
INNER JOIN empleado ON rec_idEmpleado_FK = idEmpleado
GROUP BY rec_idEmpleado_FK'),
function($join)
{
$join->on('idEmpleado', '=', 'rec_idEmpleado_FK');
})
->select('idEmpleado', 'Nombre', 'Nombre_Depto', 'Nombre_Empresa', 'Puesto', 'SueldoBase', 'Restante')
->get();
But still get the error:
check the manual that corresponds to your MySQL server version for the right syntax to use near
SELECT rec_idEmpleado_FK, SUM( SueldoBase ) AS Restante
FROM `recibos`
Any ideas why?
Ok I finally got the answer. I forgot to put the name to the inner query here is my answer. I hope it helps. I based my answer in the link that Chelsea gave me. Thanks
$pagos = DB::table('empleado')
->leftJoin('empresa', 'empresa.idEmpresa', '=', 'empleado.emp_idEmpresa_FK')
->leftJoin('departamento', 'departamento.idDepartamento', '=', 'empleado.emp_idDeparameto_FK')
->leftJoin('tipoperiodo', 'tipoperiodo.idTipoPeriodo', '=', 'empleado.emp_idTipoPeriodo_FK')
->leftjoin(
DB::raw('(SELECT rec_idEmpleado_FK, SUM( SueldoBase ) AS Restante
FROM `recibos`
INNER JOIN empleado ON rec_idEmpleado_FK = idEmpleado
GROUP BY rec_idEmpleado_FK) AS recibos1'),
function($join)
{
$join->on('idEmpleado', '=', 'rec_idEmpleado_FK');
})
->select('idEmpleado', 'Nombre', 'Nombre_Depto', 'Nombre_Empresa', 'Puesto', 'SueldoBase', 'Restante')
->get();