I am new to Laravel but I would like to create this Query(MySQL):
SELECT
*
FROM
(
SELECT
ce.empresa_id,
CONCAT(ce.nombre, ' ', ce.apellido) AS nombre,
ce.grupo_contable
FROM
cliente_empresa AS ce
UNION
SELECT
cc.empresa_id,
cc.nombre,
cc.grupo_contable
FROM
cuenta_contable AS cc
UNION
SELECT
cci.empresa_id,
cci.grupo_iva AS nombre,
cci.cuenta_contable AS grupo_contable
FROM
cuenta_contables_iva AS cci
) AS cuentasContables
WHERE
cuentasContables.empresa_id = 1
AND (cuentasContables.nombre LIKE '%a%'
OR cuentasContables.grupo_contable LIKE '%%')
Looking at Documentation I can't find the proper way to do it. Thank you.
Normally, for a query that the ORM can't manage, you would probably want to simply call \DB::raw:
$results = \DB::table('users')
->select(\DB::raw(/* your stuff here */))
However in your case, you might want to consider sticking to the ORM. It looks like you might want to try something like:
$first = DB::table('cliente_empresa')
->where('empresa_id', '=', 1);
$second = DB::table('cuenta_contable')
->where('empresa_id', '=', 1);
$results = DB::table('cuenta_contables_iva')
->where('empresa_id', '=', 1)
->union($first)
->union($second)
->get();
Obviously, you'll need to put your SELECT column statements in there as well.
Related
I need a following code to convert to Laravel query can any one help me with these.
SELECT id, `leave_name`, `total_leave_days`, leave_id, leave_taken_days FROM `leaves` AS t1 INNER JOIN ( SELECT leave_id, SUM(`leave_taken_days`) AS leave_taken_days FROM `leave_applications` WHERE user_id = 2 AND statuses_id = 2 GROUP BY leave_id ) AS t2 ON t1.id = t2.leave_id
I even tried but the output is not showing atall.
$user_leaves = DB::table('leaves')
->select('id', 'leave_name', 'total_leave_days', 'leave_id', 'leave_taken_days')
->join('leave_application', 'leave_application.leave_id', '=', 'leave.id')
->select('leave_application.leave_id', DB::raw("SUM(leave_taken_days) as leave_application.leave_taken_days"))
->where('user_id','=', 2)
->where('statuses_id','=', 2)
->get();
How can I solve this issue?
UPDATE
Relations between two models.
Leave Model
public function leave_application()
{
return $this->belongsTo(LeaveApplication::class, 'id' , 'leave_id');
}
Leave Application Model
public function leave()
{
return $this->belongsTo(Leave::class, 'leave_id', 'id');
}
Try this :
$user_leaves = Leave::select('leaves.id', 'leaves.leave_name', 'leaves.total_leave_days', 'leave_applications.leave_id', DB::raw('SUM(leave_applications.leave_taken_days) as leave_taken_days'))
->with('leave_application')
->whereHas('leave_application', function($q) {
$q->where('user_id', 2)
->where('statuses_id', 2);
})
->groupBy('leaves.id')
->get();
On this topic I would like to give my recommendations for some tools to help you out in the future.
SQL Statement to Laravel Eloquent to convert SQL to Laravel query builder. This does a decent job at low level queries. It also saves time when converting old code.
The other tool I use to view the query that is being run is Clock Work
I keep this open in a tab and monitor slow nasty queries or, also gives me perspective on how the query builder is writing SQL. If you have not use this extension I highly recommend getting and using it.
Actually I found my answer,
$user_leaves = DB::table('leaves as t1')
->select('t1.id', 't1.leave_name', 't1.total_leave_days', 't2.leave_id', 't2.leave_taken_days')
->join(DB::raw('(SELECT leave_id, SUM(leave_taken_days) AS leave_taken_days FROM leave_applications WHERE user_id = ' . $user_id . ' AND statuses_id = 2 GROUP BY leave_id) AS t2'), function ($join) {
$join->on('t1.id', '=', 't2.leave_id');
})
->get();
You can use DB:select("your query", params) and put your query and params (as an array (optional)
As below sample:
$result = DB:select("
SELECT id, `leave_name`, `total_leave_days`, leave_id, leave_taken_days
FROM `leaves` AS t1
INNER JOIN (
SELECT leave_id, SUM(`leave_taken_days`) AS leave_taken_days
FROM `leave_applications`
WHERE user_id = 2
AND statuses_id = 2
GROUP BY leave_id
) AS t2 ON t1.id = t2.leave_id" , $params
);
return response()->json($result);
This SQL:
SELECT COUNT(*) AS total_see_all_video
from users u
WHERE 7 = (SELECT COUNT(*) FROM lecciones_users lu WHERE lu.uuid = u.uuid)
I tried this code but did not work:
$data = LeccionesUsers::select(
DB::raw('COUNT(*) AS total_ase_vis_videos'),
DB::raw('where 7 = (SELECT COUNT(*) FROM lecciones_users where leccion_users.uuid = users.uuid)')
)
->join('users', 'lecciones_users.uuid', '=', 'users.uuid')
->get();
Your issue is that you are not correctly forming your query. You can do ->toSql(); instead of ->get(); and you would see the final SQL (would definitely not be the same as the one you wrote first).
So, you should have this to have the same SQL:
$total_see_all_video = LeccionesUsers::whereRaw('7 = (SELECT COUNT(*) FROM lecciones_users where leccion_users.uuid = users.uuid)')
->count();
Please, try my query (and also run ->toSql() to see if you have a correct SQL).
I would still recommend to use relationships and it is very weird to do 7 = query.
You can use
DB::query()->fromSub('Raw sql query here..')
and then can perform actions on this.For the reference you can use the documentation fromSub
You can also look into this convert this where break this query to parts to be used accordingly. You can use this section for the reference purpose:
Laravel-Raw-Expressions
Hope this will help you with the result.
Good morning,
I've been trying for quite a lot of time to translate this query(which returns an array of stdClass) into query builder so I could get objects back as Eloquent models.
This is how the query looks like untranslated:
$anketa = DB::select( DB::raw("SELECT *
FROM v_anketa a
WHERE not exists (select 1 from user_poeni where anketa_id=a.id and user_id = :lv_id_user)
Order by redni_broj limit 1"
), array( 'lv_id_user' => $id_user,
));
I have tried this, but it gives a syntax error near the inner from in the subquery:
$anketa = V_anketa::selectRaw("WHERE not exists (select 1 from user_poeni where anketa_id=a.id and user_id = :lv_id_user)", array('lv_id_user' => $id_user,)
)->orderBy('redni_broj')->take(1)->first();
The problem is this exists and a subquery in it. I couldn't find anything regarding this special case.
Assume each table has an appropriate Eloquent model.
V_anketa is a view. The db is postgresql.
As far as the query goes I believe this should work:
$anketa = V_anketa::whereNotExists(function ($query) use ($id_user) {
$query->select(DB::raw(1))
->from('user_poeni')
->where('anketa.id', '=', 'a.id')
->where('user_id', '=', $id_user);
})
->orderBy('redni_broj')
->first();
but I'm not clear on what do you mean by "assuming every table has an Eloquent model" and "V_anketa" is a view...
Assuming the SQL query is correct, this should work:
$anketa = DB::select(sprintf('SELECT * FROM v_anketa a WHERE NOT EXISTS (SELECT 1 FROM user_poeni WHERE anketa_id = a.id AND user_id = %s) ORDER BY redni_broj LIMIT 1', $id_user));
If you want to get back an Builder instance you need to specify the table:
$anketa = DB::table('')->select('');
If you however, want to get an Eloquent Model instance, for example to use relations, you need to use Eloquent.
I can't "translate" the SQL Query below to Laravel, how I can make this?
SELECT SUM(transactions.amount) AS total, products.name
FROM transactions, product_stock, product_catalog, products
WHERE transactions.id_product_stock = product_stock.id_prodct_stock
AND product_stock.id_product_catalog = product_catalog.id_product_catalog
AND product_catalog.id_product = products.id_produto
GROUP BY (products.name);
I tried this (returns error):
Transaction::join('product_stock', 'transactions.id_product_stock', '=', 'product.stock.id_product_stock')
->join('product_catalog', 'product_stock.id_product_catalog', '=', 'product_catalog.id_product_catalog')
->join('products', 'product_catalog.id_product', '=', 'products.id_product')
->groupBy('products.name')
->get([ DB::raw('SUM(transactions.amount) AS total'), DB::raw('products.name as name')]);
And this (returns empty):
DB::raw('select SUM(transactions.amount) AS total, products.name
from transactions, product_stock, product_catalog, products
where transactions.id_product_stock = product_stock.id_prodct_stock
and product_stock.id_product_catalog = product_catalog.id_product_catalog
and product_catalog.id_product = products.id_produto
group by (products.name)');
Anyone can help me?
If you want to run the raw query (and for a complex query like this, I would stick with the raw SQL because I'm more comfortable with that), what you need to do is this:
$value = DB::select('select SUM(transactions.amount) AS total, products.name
from transactions, product_stock, product_catalog, products
where transactions.id_product_stock = product_stock.id_prodct_stock
and product_stock.id_product_catalog = product_catalog.id_product_catalog
and product_catalog.id_product = products.id_produto
group by (products.name)'
);
Here's the documentation for use of the DB::select() method.
DB::raw() is used to mark part of a larger query expression as raw SQL. See http://laravel.com/docs/queries#raw-expressions for details & examples.
quick checking their documentation it looks like you want to run your entire query as a raw expression.
http://laravel.com/docs/queries#raw-expressions
hth
I'm trying to make a simple query with a subquery in a orWhere clause (with Doctrine).
As always, Doctrine tries to rename every aliases and completely destroys the queries...
Here's an example:
$q = Doctrine_Query::create()
->from('Actualite a')
->where('a.categorie_id =?', $id)
->orWhere('a.categorie_id IN (select id from cat.categorie as cat where cat.categorie_id =?)', $id)
->execute();
Which in MySQL would make something like:
SELECT *
FROM actualite a
WHERE a.categorie_id = 1 OR a.categorie_id IN (SELECT cat.id FROM categorie cat WHERE cat.categorie_id = 1);
Everything is right about it, but then again Doctrine destroys it:
Couldn't find class cat
Every time I try to do something a little complex with Doctrine, I have errors with aliases. Any advice or ideas about how to fix this?
Thanks!
The SQL example you've provided is fine but the corresponding Doctrine syntax has a couple of errors. Here's a clean version:
$q = Doctrine_Query::create()
->select('a.*')
->from('Actualite a')
->where('a.categorie_id = ?', $id)
->orWhere('a.categorie_id IN (SELECT cat.id FROM Categorie cat WHERE cat.categorie_id = ?)', $id)
->execute();
You should use createSubquery() to explicitely tell doctrine about your nested subquery. So your query should look something like this:
$q = Doctrine_Query::create()
->select('a.*')
->from('Actualite a')
->where('a.categorie_id = ?', $id)
;
$subquery = $q->createSubquery()
->select("cat.id")
->from("Categorie cat")
->where("cat.categorie_id = ?", $id)
;
$q->orWhere('a.categorie_id IN ('.$subquery->getDql().')')->execute();
Another example can be found here:
http://www.philipphoffmann.de/2012/08/taming-doctrine-subqueries/
I think you query should be like this add the select and remove as
$q = Doctrine_Query::create()
->select('a.id')
->from('Actualite a')
->where('a.categorie_id =?', $id)
->orWhere('a.categorie_id IN (select id from cat.categorie cat where cat.categorie_id =?)', $id)
->execute();
Try this may help you.
Thanks