I have a huge query that needs to be modified right now it doesn't eager load the withCount, whenever I call propertyimages_count it always return 0 instead of the correct count. But if I call $property->propertyimages()->count() it returns the correct number but it is not eager loading.
I'm not really sure why propertyimages_count, I am thinking maybe it is the alias.
$search = (isset($_GET['sSearch']) ? $_GET['sSearch'] : '');
$get = $this->method_vars($_GET);
$today = date('Y-m-d');
$where = Property::
withCount('propertyimages')
->with(['project', 'latestmaintenance', 'propertyimages'])
->join('projects', 'properties.project_id', '=', 'projects.id')
->where(function( $query ) use ($get) {
if($get['price_from'] >= 1 && $get['price_to'] <= 500000) {
$query->whereBetween('rental_price', [$get['price_from'], $get['price_to'] ]);
}
$query = $get['sqm_from'] >= 1 && $get['sqm_to'] <= 1000 ? $query->whereBetween('sqm', [$get['sqm_from'], $get['sqm_to'] ]) : $query;
if( $get['type'] != '' ) {
if( $get['type'] == 'house' ) {
$query->where('projects.type', 'Housing Project');
} else if( $get['type'] == 'condo' ) {
$query->where('projects.type', 'Condo Project');
} else if( $get['type'] == 'any' ) {
$query->whereIn('projects.type', ['Condo Project', 'Housing Project']);
}
}
$query = $get['view'] != '' ? $query->where('view', $get['view']) : $query;
$query = $get['project'] != '' ? $query->where('project_id', $get['project']) : $query;
$query = $get['bedrooms'] != '' ? $query->where('bedrooms', $get['bedrooms']) : $query;
$query = $get['bathrooms'] != '' ? $query->where('bathrooms', $get['bathrooms']) : $query;
$query = $get['property_status'] != '' ? $query->where('status', $get['property_status']) : $query;
if( $get['status'] != '' ) {
if( $get['status'] == 'rented' ) {
$query->whereRaw('CURDATE() >= check_in')->whereRaw('CURDATE() <= check_out');
} elseif( $get['status'] == 'vacant' ) {
$query->where(function($q) {
$q->whereRaw('CURDATE() NOT BETWEEN check_in AND check_out')->orWhereNull('check_in');
});
}
}
})
->orderBy('projects.name')
->orderBy('unit')
->whereRaw("(SELECT check_in
FROM property_rentals
WHERE property_rentals.property_id = properties.id
ORDER BY
CASE
WHEN check_out >= '{$today}' AND check_in <= '{$today}' THEN 0
WHEN check_in > '{$today}' THEN 1
ELSE 2
END
LIMIT 1) as check_in")
->whereRaw("(SELECT check_out
FROM property_rentals
WHERE property_rentals.property_id = properties.id
ORDER BY
CASE
WHEN check_out >= '{$today}' AND check_in <= '{$today}' THEN 0
WHEN check_in > '{$today}' THEN 1
ELSE 2
END
LIMIT 1) as check_out");
Maybe to add count images relation, something like this:
public function imagesCount()
{
return $this->hasMany('App\ProperyImage')
->selectRaw('property_id, count(*) as count)
->groupBy('property_id');
}
...and then add it to the with clause
Check this
Related
I've tried doing:
$uniquekey = '202208271120';
$results2 =DB::table('tests')
->where('usuario_id', $usuario)
->where('id_evento_test', '0')
->update([ 'id_evento_test'=> $uniquekey]);
return response()->json($results2, 201);
but when testing it in postman returned me 0.
enter image description here
Here's my code:
<?php
namespace App\Http\Controllers;
use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;
class ShowSummaryResultsController extends Controller
{
public function show(Request $request)
{
$usuario = $request->input('usuario');
$results = DB::table('tests')
->where('usuario_id', '=', $usuario)
->where('id_evento_test', '=', '0')
->get();
$resultsOkPROTANOPIA = 0;
$resultsNokPROTANOPIA = 0;
$resultsOkDEUTERANOPIA = 0;
$resultsNokDEUTERANOPIA = 0;
$resultsOkTRITANOPIA = 0;
$resultsNokTRITANOPIA = 0;
foreach ($results as $rows)
{
$image_id = $rows->image_id;
$resultado = $rows->resultado;
//$tipo = DB::table('images')
//->where('id', '=', $image_id)
//->get();
$image = 'App\Models\Image'::findOrFail($image_id);
$tipo_discromatopsia = $image->tipo_discromatopsia;
if ($tipo_discromatopsia == 'PROTANOPIA') {
if($resultado) {
$resultsOkPROTANOPIA +=1;
}else{
$resultsNokPROTANOPIA +=1;
}
}
elseif ($tipo_discromatopsia == 'DEUTERANOPIA') {
if($resultado) {
$resultsOkDEUTERANOPIA +=1;
}else{
$resultsNokDEUTERANOPIA +=1;
}
}
else {
if($resultado) {
$resultsOkTRITANOPIA +=1;
}else{
$resultsNokTRITANOPIA +=1;
}
}
//update event_id with a unique key
//$uniquekey = 202208271116;
//$results->id_evento_test = $uniquekey;
//$results->save();
}
$porc=0;
if (($resultsOkPROTANOPIA + $resultsNokPROTANOPIA) >0)
{ $porc=$resultsOkPROTANOPIA / ($resultsOkPROTANOPIA + $resultsNokPROTANOPIA ) * 100; }
$result[0] = array("tipo" =>'PROTANOPIA',"ResOK" =>$resultsOkPROTANOPIA,"ResNOK" =>$resultsNokPROTANOPIA,"Porc" =>$porc);
$porc=0;
if (($resultsOkDEUTERANOPIA + $resultsNokDEUTERANOPIA ) >0)
{$porc=$resultsOkDEUTERANOPIA / ($resultsOkDEUTERANOPIA + $resultsNokDEUTERANOPIA ) * 100;}
$result[1] = array("tipo" =>'DEUTERANOPIA',"ResOK" =>$resultsOkDEUTERANOPIA,"ResNOK" =>$resultsNokDEUTERANOPIA,"Porc" =>$porc);
$porc=0;
if (($resultsOkTRITANOPIA + $resultsNokTRITANOPIA )>0)
{$porc=$resultsOkTRITANOPIA/ ($resultsOkTRITANOPIA + $resultsNokTRITANOPIA )* 100;}
$result[2] = array("tipo" =>'TRITANOPIA',"ResOK" =>$resultsOkDEUTERANOPIA,"ResNOK" =>$resultsNokDEUTERANOPIA,"Porc" =>$porc);
$min = min($result[0]['Porc'],$result[1]['Porc'],$result[2]['Porc']);
$result[3] = array("tipo" =>'RESULTADOS',"index"=>$min,"Tipo"=>$result[$min]['tipo'], );
$uniquekey = '202208271120';
$results2 =DB::table('tests')
->where('usuario_id', $usuario)
->where('id_evento_test', '0')
->update([ 'id_evento_test'=> $uniquekey]);
return response()->json($results2, 201);
//return response()->json($result, 201);
}
}
If you need value of column after successful updating then read this example please:
$uniquekey = '202208271120';
try {
DB::table('tests')
->where('usuario_id', $usuario)
->where('id_evento_test', 0)
->update(['id_evento_test' => $uniquekey]);
$results2 = $uniquekey;
return response()->json($results2, 201);
} catch (\Illuminate\Database\QueryExeption $e) {
return response()->json(['error' => 'Unsuccessful Update']);
}
You can use first or get to retrieve all the data from table test or only column id_evento_test. So $results2 could have all data or only part of data as you need.
in this code $results2 =DB::table('tests') you are storing the result of the database query to $result2 which is 0 or 1 and 0 means that nothing was updated and 1 means that the update was done successfully.
if you want to return the $uniquekey then assign it to $result2:
$results2 = $uniquekey;
return response()->json($results2, 201);
or just return $uniquekey:
return response()->json($uniquekey, 201);
I wrote the code snippet inside my Laravel controller and I want to sort the products by product number first and then sort the previously sorted products by inventory.
My problem is that the first sort is executed inside the written command but the second sort does not happen.
My code snippet is as follows:
DB::statement("SET SQL_MODE=''");//this is for fix groupby error!
$productdetail = Sa_product::leftJoin('sa_product_allproperties', 'sa_products.productid', 'sa_product_allproperties.product_id')->where('sa_products.product_status', '1');
if (isset($data['static']) && $data['static']['search_products'] != '') {
$search_word = $data['static']['search_products'];
DB::statement("SET SQL_MODE=''");//this is for fix groupby error!
$exploded_word = explode(',', $search_word);
$counter = 0;
$productdetail = $productdetail->where(function ($q) use ($exploded_word, $counter) {
$counter = 0;
foreach ($exploded_word as $word) {
if ($counter == 0) {
$q->where('sa_products.title', 'LIKE', "%{$word}%");
} else {
$q->orwhere('sa_products.title', 'LIKE', "%{$word}%");
}
$counter++;
}
});
}
$data['staticcats'] = explode(',', $data['static']['product_cats']);
if (isset($data['static']) && $data['static'] != '') {
$explodecats = explode(',', $data['static']['product_cats']);
unset($explodecats[0]);
array_pop($explodecats);
} else {
$explodecats = [];
}
if (isset($explodecats) && $explodecats != []) {
$counter = 0;
$productdetail = $productdetail->where(function ($q1) use ($explodecats, $counter) {
$counter = 0;
foreach ($explodecats as $cats) {
if ($counter == 0) {
$q1->where('sa_products.catid', 'LIKE', "%,{$cats},%");
} else {
$q1->orWhere('sa_products.catid', 'LIKE', "%,{$cats},%");
}
$counter++;
}
});
$productdetail = $productdetail->orderBy('visited_counter', 'DESC');
}
$data['staticcats'] = explode(',', $data['static']['product_brands']);
if (isset($data['static']) && $data['static'] != '') {
$explodebrands = explode(',', $data['static']['product_brands']);
unset($explodebrands[0]);
array_pop($explodebrands);
} else {
$explodebrands = [];
}
if (isset($explodebrands) && $explodebrands != []) {
$counter = 0;
$productdetail = $productdetail->where(function ($q2) use ($explodebrands, $counter) {
$counter = 0;
foreach ($explodebrands as $brands) {
if ($counter == 0) {
//$q1->where('brand_id','LIKE', "%,{$brands},%");
$q2->where('sa_products.brand_id', "{$brands}");
} else {
//$q1->orWhere('brand_id','LIKE', "%,{$brands},%");
$q2->orWhere('sa_products.brand_id', "{$brands}");
}
$counter++;
}
});
}
$productdetail = $productdetail->orderBy('sa_products.productid','DESC')->orderBy('sa_product_allproperties.stock_count','DESC')->groupBy('sa_products.productid')->paginate(20);
if (isset($productdetail) && $productdetail->count()>0)
{
$data['searched_products'] = $productdetail;
}
After executing the above code, the received products are sorted by product number, ie the orderBy('sa_products.productid', 'DESC') occurs, but the second sorting is done with the orderBy('sa_product_allproperties.stock_count', 'DESC') Which is not run for inventory sorting.
Can anyone help me solve this problem?
I am trying to read excel file and store that data in database. This excel file is kind of template. one would be default template and this template could be changed in future. Currently i am reading that file with many if conditions .I personally think that it isn't best way to read excel file so looking for better way.
this procedure is divided into two functions
public function importManifestFile(Request $request)
{
$path = $request->file('manifest_file')->getRealPath();
$spreadsheet = IOFactory::load($path);
$sheetData = $spreadsheet->getActiveSheet()->toArray(null, true, true, true);
foreach ($sheetData as $rows => $ManifestConsignments) {
if ($rows >= 9 && $rows <= 37) {
$this->manifestConsignment($ManifestConsignments);
}
}
}
//import file manifest consignment function
public function manifestConsignment($ManifestConsignments)
{
$consignment = new Consignment;
foreach ($ManifestConsignments as $key => $ManifestConsignment) {
if ($key == 'A') {
}
if ($key == 'B') {
$consignment->delivery_date = $ManifestConsignment;
}
if ($key == 'C') {
$addressId = $ManifestConsignment;
}
if ($key == 'D') {
$companyName = $ManifestConsignment;
}
if ($key == 'E') {
$streetAddress = $ManifestConsignment;
}
if ($key == 'F') {
$suburb = $ManifestConsignment;
}
if ($key == 'G') {
$state = $ManifestConsignment;
}
if ($key == 'H') {
$postCode = $ManifestConsignment;
}
if (isset($postCode)) {
if (Address::where('company_name', $companyName)->where('street_address', $streetAddress)->where('suburb', $suburb)->where('state', $state)->where('postcode', $postCode)->exists()) {
$deliveryAddress = Address::where('company_name', $companyName)->where('street_address', $streetAddress)->where('suburb', $suburb)->where('state', $state)->where('postcode', $postCode)->first();
$deliveryAddressId = $deliveryAddress->id;
$consignment->delivery_address = $deliveryAddressId;
unset($postCode);
} else {
$address = new Address;
$address->company_name = $companyName;
$address->street_address = $streetAddress;
$address->suburb = $suburb;
$address->postcode = $postCode;
$address->state = $state;
$address->save();
$consignment->delivery_address = $address->id;
unset($postCode);
}
if ($key == 'I') {
$consignment->carton = $ManifestConsignment;
}
if ($key == 'J') {
$consignment->pallet = $ManifestConsignment;
}
if ($key == 'K') {
$consignment->weight = $ManifestConsignment;
}
if ($key == 'L') {
$consignment->invoice_value = $ManifestConsignment;
}
if ($key == 'M') {
if (!empty($ManifestConsignment)) {
$consignment->cash_on_delivery = $ManifestConsignment;
}
}
if ($key == 'N') {
$consignment->product_type_id = 1;
}
if ($key == 'O') {
$consignment->comment = $ManifestConsignment;
}
$consignment->customer_id =1;
$consignment->status = 'In Warehouse';
$consignment->product_type_id = 1;
$consignment->save();
}
}
}
$key
in code is column name of excel file . i am checking what is column name and storing data according to that.
public function shirts($type = '') {
{
if ($type == 'glass') {
$shirt = Product::where('category_id', '1') - > get();
}
elseif($type == 'ic') {
$shirt = Product::where('category_id', '2') - > get();
}
elseif($type == 'cover') {
$shirt = Product::where('category_id', '3') - > get();
} else {
$shirt = Product::all();
}
$products = Category::find($shirt);
return view('front.shirt', compact('products', 'shirt'));
}
}
can some one help me in minimising this Controller I don't want to use if else statement
I ask the question before I was not getting anymore replies and I decide to re-post it if that will help. I hope i'm not doing anything wrong by re-posting?
$total_cost_for_A = $this->admin_model->total_cost_for_A($branch, $department, $date);
$total_cost_for_B = $this->admin_model->total_cost_for_B($branch, $department, $date);
The variables $total_cost_for_A and $total_cost_for_B hold the returned value from a mysql summation queries in the model. The queries return false if no record was found. Now, I'm trying to perform this operation.
if(($total_cost_for_A === FALSE) && ($total_cost_for_B === FALSE))
{
$data['no_record'] = 'No Record Found!';
$this->load->view('admin/bookings', $data);
}
else
{
$this->load->view('admin/summary', $data);
}
This test always fail and execute the else statement instead, which is not what. Any assistance will be appreciated. Thanks
Here are the functions
function total_cost_for_A($branch, $department, $date)
{
if($branch == 'Head Office' && $department == 'Summary')
{
$select_amount_paid = 'SELECT SUM(total_amount) total_amount FROM graphics_booking AS bk
WHERE bk.date = "'.$date.'"';
}
$result = $this->db->query($select_amount_paid);
if($result->num_rows() > 0)
{
return $result;
}
else
{
return FALSE;
}
}
function total_cost_for_B($branch, $department, $date)
{
if($branch == 'Head Office' && $department == 'Summary')
{
$total_LF_amount = 'SELECT SUM(total_amount) total_amount FROM large_format_print
WHERE date = "'.$date.'"';
}
$result = $this->db->query($total_LF_amount);
if($result->num_rows() > 0)
{
return $result;
}
else
{
return FALSE;
}
}
Try to change like this
$select_amount_paid = 'SELECT SUM(total_amount) total_amount FROM graphics_booking AS bk
WHERE date = '.$date;//i assume that date is an colum from graphics_booking
you are wrong with "bk.date" you can give directly if it is in your table with where condition and also try to avoid the same name for the function in the model and the varaible assigned.Try to change as different.otherwise your code looks good
No when u return u cannot return the entire , you need to return a row
so you need to do in your model as :
function total_cost_for_A($branch, $department, $date)
{
if($branch == 'Head Office' && $department == 'Summary')
{
$select_amount_paid = 'SELECT SUM(total_amount) total_amount FROM graphics_booking AS bk
WHERE bk.date = "'.$date.'"';
}
$result = $this->db->query($select_amount_paid);
if($result->num_rows() > 0)
{
return $result->row(); // you missed out here
}
else
{
return FALSE;
}
}
Same for the total_cost_for_B()