How to optimize the following query Laravel? - laravel

I have the code which is working perfectly fine.
$amenityCategoryMapping1 = AmenityCategoryMapping::where('property_id', $property->id)
->orderBy('amenity_name','asc')
->orderBy('updated_at','desc')
->pluck('category_id', 'amenity_name')->toArray();
$amenityCategoryMapping2 = AmenityCategoryMapping::where('company_id', $property->company_id)
->orderBy('amenity_name','asc')
->orderBy('updated_at','desc')
->pluck('category_id', 'amenity_name')->toArray();
$amenityCategoryMapping3 = AmenityCategoryMapping::whereNull('property_id')
->orderBy('amenity_name','asc')
->orderBy('updated_at','desc')
->pluck('category_id', 'amenity_name')->toArray();
$amenityCategoryMapping = array_merge($amenityCategoryMapping3, $amenityCategoryMapping2, $amenityCategoryMapping1 );
However, currently I am executing 3 different query to extract data from the same table just using different parameters. Is there any way to minimize this query requests and still receiving the same results?
Currently, while plucking if two array has the same key then I am replacing amenityCategoryMapping3 by amenityCategoryMapping2 and that by amenityCategoryMapping1. That is more priority should be given to amenityCategoryMapping1

Try using orWhere function
$amenityCategoryMapping1 = AmenityCategoryMapping::where('property_id', $property->id)
->orWhere('company_id', $property->company_id)
->orWhereNull('property_id')
->orderBy('amenity_name','asc')
->orderBy('updated_at','desc')
->pluck('category_id', 'amenity_name')->toArray();

Related

Efficient way to query database with multiple conditions in laravel

Is it possible to make this a single query?
$yl_min = DB::connection($this->db2)->table('historical')
->where([['slug','=',$crypto_id],['low_usd','!=', null]])
->whereBetween('created_time',[$this->range_1y,$this->hislatest])
->min('low_usd');
$yl = DB::connection($this->db2)->table('historical')
->select('id','coin','low_usd','created_time','created_at')
->where([['slug','=',$crypto_id],['low_usd',$yl_min]])
->whereBetween('created_time',[$this->range_1y,$this->hislatest])
->first();
I've tried this but no luck:
$yl = DB::connection($this->db2)->table('historical')
->select('id','coin','created_time','created_at',DB::raw('SELECT MIN(low_usd) as low_usd'))
->where([['slug','=',$crypto_id],['low_usd','!=', null]])
->whereBetween('created_time',[$this->range_1y,$this->hislatest])
->first();
After looking at your query code, I found the two query condition is same, and you just want to get min low_usd record,
I think you can just use the multiple condition and ORDER BY low_usd ASC, then take the first one:
$yl = DB::connection($this->db2)->table('historical')
->where([['slug','=',$crypto_id],['low_usd','!=', null]])
->whereBetween('created_time',[$this->range_1y,$this->hislatest])
->orderBy('low_usd','asc')
->select('id','coin','low_usd','created_time','created_at')
->first();
After this, if you want to make this query more efficient,
you need to add index on slug, low_usd, created_time

Laravel count raw query always return zero

I am working with multiple databases in single project. When I run simple raw query to get another database table count but it always return zero instead of actual counts. Even I have more than 1 million records in table.
I run raw query in following formats but result is zero
$dbconn = \DB::connection("archive_db");
$dbconn->table('activities_archived')->count()
$sql = "SELECT COUNT(*) as total FROM activities_archived";
$result = \DB::connection("archive_db")->select(\DB::raw($sql));
Event I have set the database connections strict option to false but still facing same issue.
Now I am totaly stuck that why this issue is coming
$someModel->setConnection('mysql2');
$something = $someModel->count();
return $something;

why when i select all data is showing but when i use find or where data not showing even if i check with dd

some make me confusing in laravel when i use all() data is showing but when i select find or where data not showing when i use dd function in laravel
//$regency = Regency::find(1101);
//$regency = Regency::where('number','=',$prov_id);
$regency = DB::table('regencies')->where('province_id', $prov_id);
dd($regency);
i try use eloquent and query builder but still same result.
those is result in dd if i using query builder, but why when i use select all data is showing
What you are showing is the Query Builder you need to execute it with ->get() to get the Collection.
You have to get the data from the query builder in order to receive the results as a collection of objects
// $regency = Regency::findOrFail(1101);
// $regency = Regency::where('number', $prov_id)->get();
$regency = DB::table('regencies')->where('province_id', $prov_id)->get();
dd($regency);
Writing a query builder just produces the SQL query but doesn't actually execute/run it
Hope this helps

no results if setting more than 2 parameters to the querybuilder - laravel-doctrine/orm + Lumen + oracle

I am facing a strange problem trying to execute a simple request using laravel-doctrine/orm v1.2.5 on Lumen v5.2.7. with an Oracle database.
When I create a query with the query builder containing more than 2 parameters, I get no results, even though I am expecting a result set.
$conn = $this->getEntityManager()->getConnection();
$queryBuilder = $conn->createQueryBuilder();
$queryBuilder->select('*')
->from('SYNCHS')
->where('SYNCHS.CLIENT_ID = :clientId')
->andWhere('SYNCHS.TOP_CLIENT_ID = :topClientId')
->andWhere('SYNCHS.ID = :synchId');
$queryBuilder->setParameter('clientId', $clientId)
->setParameter('topClientId', $topClientId)
->setParameter('synchId', $synchId);
echo $queryBuilder->getSQL();
var_dump($queryBuilder->getParameters());
$stmt = $queryBuilder->execute();
var_dump($stmt);
$results = $stmt->fetchAll();
dd($results);
If I comment any one of the where/addwhere clause, I end up with the expected result set, but if I have more than 2 parameters bound in the query, it returns nothing (of course it should return something with the passed parameters).
For every scenari:
I can see all my parameters are bound in the query builder var_dump($queryBuilder->getParameters());
Copy paste of the echo $queryBuilder->getSQL(); in Toad (oracle) setting the parameters with the values displayed by the var_dump($queryBuilder->getParameters()); give me 1 row (expected result). So I am sure that my query is correct.
I've looked for hours on google but no relevant result appeared for this problem. Thanks

How to combine and & or operators in grocery crud

I am using codeigniter and grocerycrud, I want to set a table with grocerycrud in this way:
SELECT * FROM `dashboard`.`medidas_ludlum`
where FK_ludlum='190.26.88.131'
and date>= '2014-03-04 09:40:00'
and date<= '2014-03-05 09:40:00'
and (error_code=1 or audio_status=1);
I tried to do that in this way:
$uno='1';
$crud2 = new grocery_CRUD();
$crud2->set_theme('datatables');
$crud2->where('FK_ludlum',$ludlum_id);
$crud2->where('date>=',$fechainicio);$crud2->where('date<=',$fechafin);
$crud2->where('error_code =',$uno);
$crud2->or_where('audio_status =',$uno);
$crud2->set_table('medidas_ludlum');
$crud2->columns('measurement', 'fecha', 'audio_status', 'high_alarm_status', 'low_alarm_status','over_range_status','monitor_status','error_code');
$crud2->set_language("spanish");
$crud2->unset_add();$crud2->unset_delete();$crud2->unset_edit();$crud2->unset_read();
$data['crud2'] = $crud2->render();
However it's not giving the right results, for example I am getting rows that have a date out of the range, is there a way to get that CRUD set up?
Grocery curd is also using codeigniter's active record so you can write your where() with grouped conditions as below,no need to use or_where() function
$crud2->where('(error_code ='.$uno.' OR audio_status ='.$uno.')',null,FALSE);
or
$crud2->where('(error_code =1 OR audio_status =1)',null,FALSE);
The problem in your query is when you use or_where() function it produces where clause as and error_code=1 or audio_status=1 and using approach that i have provide will give you the where clause as and (error_code=1 or audio_status=1) a grouped condition
API and Functions list

Resources