laravel: multiple select query - php

I understand that to do a select query is
$bearLawly = Bear::where('name', '=', 'Lawly')->first();
but how to I do a select query such as
SELECT * FROM bear where name = 'abc' AND age => '5' AND title = 'kid' ORDER BY name LIMIT 5, 10
Thanks!

You may try this:
$bearLawly = Bear::where('name', 'abc') // By default = will be used, so optional
->where('age', '>=', '5')
->where('title', 'kid')
->orderBy('name') // or orderBy('name', 'desc') for reverse
->take(5)->skip(10)->get();
According to following query:
SELECT * FROM bear where name = 'abc' AND age => '5' AND title = 'kid' ORDER BY name LIMIT 5, 10

Just chain them:
$bearLawly = Bear::where('name', 'Lawly')->where('age', '5')->first();

Related

performing raw query into query builder in yii2

How can I convert this raw query into query builder yii2 as I am getting the record using sub-query:
RAW QUERY:
SELECT *
FROM (
SELECT DISTINCT `comp`.*,TIMESTAMPDIFF(HOUR,comp.created_date,comp.updated_date)
AS hours
FROM `complaints` `comp`
INNER JOIN `complaint_log` `comp_log` ON comp_log.`comp_id` = comp.`id`
WHERE ((comp.name LIKE '%%' OR comp.id LIKE '%%' OR comp.phone_no LIKE '%%')
AND DATE(comp.created_date)
BETWEEN '2018-01-01' AND '2020-03-20')
AND (comp.is_delete = 0)
ORDER BY `comp`.`id` DESC, `comp`.`created_date` DESC)
AS cte_name WHERE hours > 120;
Yii2 Query
$query = (new \yii\db\Query())
->select('comp.*')
->from('complaints comp
->distinct()
->innerJoin('complaint_log as comp_log', 'comp_log.`comp_id` =comp.`id`')
->where($search)
->andWhere('comp.is_delete = 0')
->orderBy("comp.id DESC")
->addOrderBy('comp.created_date DESC');
Try following code:
$subquery = (new \yii\db\Query())
->select(['comp.*', 'TIMESTAMPDIFF(HOUR, comp.created_date, comp.updated_date) AS hours'])
->distinct()
->from('complaints comp')
->innerJoin('complaint_log comp_log', 'comp_log.comp_id = comp.id')
->where(['or',
['like', 'comp.name', $search_name],
['or',
['like', 'comp.id', $search_id],
['like', 'comp.phone_no', $search_phone],
]
])
->andWhere('DATE(comp.created_date) BETWEEN :cStart AND :cEnd', [':cStart' => '2018-01-01', ':cEnd' => '2020-03-20'])
->andWhere(['comp.is_delete' => 0])
->orderBy(['comp.id' => SORT_DESC, 'comp.created_date' => SORT_DESC])
;
$query = (new \yii\db\Query())
->select('cte_name.*')
->from(['cte_name' => $subquery])
->where(['>', 'cte_name.hours', 120])
;
You can use createCommand() function: use below query.
$connection = \Yii::$app->db;
$query = $connection->createCommand(
'
SELECT * FROM (
SELECT DISTINCT comp.*,TIMESTAMPDIFF(HOUR,comp.created_date,comp.updated_date) AS hours
FROM complaints comp
INNER JOIN complaint_log comp_log ON comp_log.comp_id = comp.id
WHERE ('.$search.')
AND (comp.is_delete = 0)
ORDER BY comp.id DESC, comp.created_date DESC
) AS cte_name WHERE hours > 120;
');
$data = $query->queryAll();
Put your raw query in createCommand() function. Here i used $search variable as you used in your sub query

Use number in where condition in Laravel Query

The below query works well in mysql but how to represent the same thing using Laravel.
select * from user_subscription where vendor_id = 'user_100'
and 0 = (select count(*) from user_restricted_dates where vendor_id = 'user_100')
I tried with code but gives error as unknown column '0' in where clause
$list = UserSubscription::where('vendor_id', '=', $vendor_obj->vendor_id)
->where(0, '=', "(select count(*) from user_restricted_dates where vendor_id = 'user_100'")
->get();
Well the error indicates what it is but how to represent it
The where method of the Query Builder maps the first value you pass to a field in the model. You'd have to use the whereRaw method instead.
$list = UserSubscription::where('vendor_id', '=', $vendor_obj->vendor_id)
->whereRaw("0 = (select count(*) from user_restricted_dates where vendor_id = 'user_100')")
->get();

How to write union query in Laravel?

I'm using laravel 5.0 and I have mysql query:
SELECT surat_masuk.id_surat,
surat_masuk.nomor_surat
FROM surat_masuk
WHERE ! EXISTS (SELECT *
FROM file_replace
WHERE id_surat_lama = surat_masuk.id_surat)
AND surat_masuk.id_jenis_surat = '6'
AND surat_masuk.deleted = '0'
UNION
SELECT id_surat_lama
FROM file_replace
WHERE id_surat_baru = '38'
And I write that in my laravel code into:
$nomor_surat1 = DB::table('surat_masuk')->select('id_surat', 'nomor_surat')
->where('id_jenis_surat', '=', $id_jenis_surat)
->where(function ($query) {
$query->where('masa_berlaku_to', '>=', date('Y-m-d'))
->orwhere('masa_berlaku_to', '=', '0000-00-00');
})
->whereExists(function ($query) {
$query
->from('file_replace')
->where('id_surat_lama', '==', 'surat_masuk.id_surat');
})
->where('deleted', '=', '0');
$nomor_surat = DB::table('file_replace')->join('surat_masuk', 'file_replace.id_surat_lama', '=', 'surat_masuk.id_surat')
->select('id_surat_lama', 'nomor_surat')
->where('id_surat_baru', '=', $id_surat_baru)
->union($nomor_surat1)->get();
But I've got nothing showed. Do you know where is the mistakes?
Well, I finally using raw query..
$results = DB::select( DB::raw("SELECT * FROM some_table WHERE some_col = '$someVariable'") );
Please see the answer, that might help you..
SELECT surat_masuk.id_surat,
surat_masuk.nomor_surat
FROM surat_masuk
WHERE ! EXISTS (SELECT *
FROM file_replace
WHERE id_surat_lama = surat_masuk.id_surat)
AND surat_masuk.id_jenis_surat = '6'
AND surat_masuk.deleted = '0'
UNION
SELECT id_surat_lama
FROM file_replace
WHERE id_surat_baru = '38'
//converted to laravel elequent query.
$first_sql=DB::table('surat_masuk as sm1')
->whereNotExists(function($query) {
$query->from('file_replace as fr1')
->where('fr1.id_surat_lama','sm1.id_surat');
})->where('sm1.id_jenis_surat',6)
->where('sm1.deleted',0)
->select('sm1.id_surat', 'sm1.nomor_surat' );
//will return an elequent object, append '->get()' to see the output seperately
$actual_result=DB::table('file_replace as fr2')
->where('fr2.id_surat_baru',38)
->select('fr2.id_surat_lama')
->union($first_sql)
->get();
//will return an array of result set

Doctrine 2: Getting records based on at least one record with a specific attribute?

In my Symfony project in an SQL query I would like to retrieve all customers with at least one active order. Here comes my query in my Orders Repository:
$query = $this->createQueryBuilder( 'o' )
->select( [
'c.firstname',
'c.lastname'
] )
->join( '\MyBundle\Entity\Contacts',
'c',
'WITH',
'c.crmid = o.idCustomer' );
There is a field in my Orders table called "isActive" which can have the value 0 or 1. How do I achieve that I only get those customers who have at least one order with isActive = 1, considering also orders which are not active anymore?
You must do a Subquery, like this:
$query = $this->createQueryBuilder( 'o' )
->select(
'c.firstname',
'c.lastname'
)
->addSelect('(
SELECT COUNT(or.id)
FROM MyBundle\Entity\Orders AS or
WHERE or.contact = c.id
AND or.isActive = 1
) as orders_num
')
->join( '\MyBundle\Entity\Contacts',
'c',
'WITH',
'c.crmid = o.idCustomer' )
->having('orderes_num > 0')

How do I build a UNION query with ORDER BY and GROUP BY in Kohana's query builder?

I'm trying to build a UNION query using Kohana's query builder. Everything works fine until I add a GROUP BY or ORDER BY clause.
Here is the code I'm using (simplified):
$query1 = DB::select('p.name')
->from(array('person', 'p'))
->where('p.organization', 'LIKE', 'foo%')
->limit(10);
$names = DB::select('sh.name')
->union($query1, FALSE)
->from(array('stakeholder', 'sh'))
->where('sh.organization', 'LIKE', 'foo%')
->group_by('name')
->order_by('name')
->limit(10)
->execute()
->as_array();
Instead of adding the GROUP BY and ORDER BY at the end of the entire query, it's adding it immediately after the second query.
This is the SQL this generates:
SELECT sh.name FROM stakeholder AS sh WHERE sh.organization LIKE 'foo%'
GROUP BY name ORDER BY name LIMIT 10
UNION
SELECT p.name from person AS p WHERE p.organization LIKE 'foo%' LIMIT 10;
What I want is:
SELECT sh.name FROM stakeholder AS sh WHERE sh.organization LIKE 'foo%'
UNION
SELECT p.name from person AS p WHERE p.organization LIKE 'foo%'
GROUP BY name ORDER BY name LIMIT 10;
The clauses here are applied from the first query set up in the union() method, so just reverse where you're putting them:
$query1 = DB::select('p.name')
->from(array('person', 'p'))
->where('p.organization', 'LIKE', 'foo%')
->group_by('name')
->order_by('name')
->limit(10);
$names = DB::select('sh.name')
->union($query1, FALSE)
->from(array('stakeholder', 'sh'))
->where('sh.organization', 'LIKE', 'foo%')
->execute()
->as_array();
You can also remove that superfluous ->limit(10) from $names since it will be ignored and superseded by the one in $query1.
You can also extend Kohana_ORM using ORM's db_pending:
class ORM extends Kohana_ORM {
public function union($table, $all = TRUE)
{
// Add pending database call which is executed after query type is determined
$this->_db_pending[] = array(
'name' => 'union',
'args' => array($table, $all),
);
return $this;
}
}
Usage:
ORM::factory('MyModel')
->union(DB::select(DB::expr("'RP' id, 'Pasantías' name, 'Pasantías' short_name, 'R' parent_id, null data")))
->union(DB::select(DB::expr("'RC' id, 'Capacitación' name, 'Capacitación' short_name, 'R' parent_id, null data")))
->join(['catalogo', 'p'])->on('catalogo.parent_id', '=', 'p.id')
->where('p.parent_id', 'is', NULL)
->where('catalogo.id', 'not in', ['RV', 'RPA', 'RPT']);
That answer from 2011 isn't working in Kohana 3.3.
But I found this module: https://github.com/Invision70/kohana-orm-union

Categories