laravel mysql -problem with data extraction - laravel

hello I learn laravel I have a problem I have a mysql database with a table breakdowns in it columns machine_name and data_zgnoszeniaawarii, I need help because I do not know how to extract data from the database in the form
machine name and number of occurrences, how to pass it to blade.php, e.g.
machine name
machine - NR01
number of appearances
5
is it something like this:
$quantity_of_of_machine =DB::select( DB::raw("SELECT numer_maszyny, COUNT(*) FROM `awaries` GROUP BY numer_maszyny") );
or
$quantity_of_of_machine = DB::table('awaries')
->select('numer_maszyny')
->groupBy('numer_maszyny')
->where('data_zgloszenia', '!=', null)
->where('user_id', '=', $user_id)
->count();

It is better if you add the table scheme, but now I can say you should do something like this:
DB::table('awaries')->selectRaw('numer_maszyny, count(*)')
->groupBy('numer_maszyny')
->where('data_zgloszenia', '!=', null)
->where('user_id', '=', $user_id); // ->get();

Related

How to get created column using SelectRaw and use it inside whereBetween

I've got a laravel eloquent query which uses selectRaw and whereBetween:
$offset = '+8:00';
$d["records"] = data_entries::select("*")
->selectRaw("CONVERT_TZ (testTime, '+0:00', '{$offset}') as convertedTime")
->whereBetween("testTime", $filters['duration'])
->where('data_entries.patientID_FK', '=', $patient['patientID'])
->leftjoin('additional_notes', 'ID', '=', 'additional_notes.entryID_FK')
->get();
So this query works and I can get convertedTime data. But I want to use convertedTime instead of testTime in whereBetween like this:
$d["records"] = data_entries::select("*")
->selectRaw("CONVERT_TZ (testTime, '+0:00', '{$offset}') as convertedTime")
->whereBetween("convertedTime", $filters['duration'])
->where('data_entries.patientID_FK', '=', $patient['patientID'])
->leftjoin('additional_notes', 'ID', '=', 'additional_notes.entryID_FK')
->get();
but I got error saying unknown column 'convertedTime'. Is there a way to get the date that was converted based on timezone inside the whereBetween?
You cannot refer to an alias defined in the select clause in the where clause at the same level of the query. But it just so happens that MySQL has overloaded the HAVING operator such that it can be used in place of WHERE, with the added feature that it can also refer to aliases. Consider the following version:
$d["records"] = data_entries::select("*")
->selectRaw("CONVERT_TZ (testTime, '+0:00', '{$offset}') AS convertedTime")
->where('data_entries.patientID_FK', '=', $patient['patientID'])
->leftjoin('additional_notes', 'ID', '=', 'additional_notes.entryID_FK')
->havingRaw("convertedTime >= ? AND convertedTime <= ?", $filters['duration'])
->get();

Laravel Query Builder Foreach Loop how do I reference a field that exists in both join tables

The id field in the foreach loop exists in both of the tables that I am joining, I need to reference it to one table only (ie. program_types.id) in the foreach loop:
$program_details = DB::table('program_allocation')
->where('twilio_wa_from_no', '=', $tophonenumber)
->where('twilio_sid' , $account_sid)
->join('program_types', 'program_allocation.program_type', '=', 'program_types.id')
->get();
foreach ($program_details as $program) {
$program_allocation_id = $program->id;
}
You can use select('program_allocation.*', 'program_types.id AS program_type_id') to specify which columns of which tables included in query you want to use.
$program_details = DB::table('program_allocation')
->where('twilio_wa_from_no', '=', $tophonenumber)
->where('twilio_sid', $account_sid)
->join('program_types', 'program_allocation.program_type', '=', 'program_types.id')
->select('program_allocation.*', 'program_types.id AS program_type_id')
->get();
You can check it on official Laravel documentation: https://laravel.com/docs/9.x/queries#inner-join-clause
Select field and give one of the join table id an alias
$program_details = DB::table('program_allocation')
->join('program_types', 'program_allocation.program_type', '=', 'program_types.id')
->select('program_types.*', 'program_allocation.id as allocationID', )
->where('twilio_wa_from_no', '=', $tophonenumber)
->where('twilio_sid' , $account_sid)
->get();

Using day, Month or Year as MYSQL query filter in Laravel

In my code, i am querying a database by accepting month and year input from user.
I have tried writing it the normal PHP way and other ways i can find online but none seems to be working. here is the code i am using currently
$salesmonth = $request->input('mn');
$salesyear = $request->input('yr');
$id = Auth::user()->id;
$comm = \DB::table('bakerysales')
->where([
['customer_id', '=', $id], [MONTH('sales_date'), '=', $salesmonth], [YEAR('sales_date
'), '=', $salesyear]
])
->get();
return view::make('showCommission')->with('comm', $comm);
I expect the query to return data from rows that match user selected month and year
Laravel comes with a few different where clauses for dealing with dates e.g.
whereDate / whereMonth / whereDay / whereYear.
This means that your controller method can look something like:
$comm = \DB::table('bakerysales')
->where('customer_id', auth()->id())
->whereMonth('sales_date', $request->input('mn'))
->whereYear('sales_date', $request->input('yr'))
->get();
return view('showCommission', compact('comm'));

Counting columns with if conidition in query

Counting only columns in which, Buy_Rate is more than Sell_Rate.
My query is not resulting as per expected, it is resulting me wrong.
$user_id = Auth::user()->id;
$losing_trades_count = FinalTrade::where('user_id', '=', $user_id)->where('buy_rate', '<', 'sell_rate')->get()->count();
Inverse: If sell_rate is more than buy_rate then only, count the columns.
You can use whereColumn
$losing_trades_count = FinalTrade::where('user_id', '=', $user_id)
->whereColumn('buy_rate', '<', 'sell_rate')
->count();
Also there is no need to call get() when you need count() from query builder
laravel eloquent where don't support comparing columns. so you need use raw SQL in order to compair two columns. you can do something like,
$user_id = Auth::user()->id;
$losing_trades_count = FinalTrade::where('user_id', '=', $user_id)->whereRaw('buy_rate < sell_rate')->get()->count();
hope this helps!

Querying related table data with Eloquent

i have a problem trying to get records from a model based on a related table.
I have two tables one called leads and one called recycle_logs, my app will basically send the same record in the leads table like once a month, and when it does so i'll store a new record in recycle_logs.
The problem is that i need to select all leads with a specific campaign_id value and that have a specific status that is different from invalid, so far so good, now the problem is i need to get them only if they don't have any recycleLogs associated with them OR if the last recycleLog associated with that particular lead is older than 30 days ago for instance.
What i currently have looks somewhat like this.
$leads = $this->leadModel->where(Lead::CAMPAIGN_ID, $this->campaignID)
->where(Lead::DUPLICATED, Lead::DUPLICATED_NO)
->where(Lead::LEAD_STATUS, "!=" ,Lead::LEAD_STATUS_INVALID)
->orderBy(Lead::CREATED_AT, 'desc')
->with(
['leadRecyclingLog' => function($query) {
$query->where(LeadRecyclingLog::CREATED_AT, '<', (new Carbon())->subDays($this->configRecyclingDays))
->orWhere(LeadRecyclingLog::ID, null);
}]
)
->get();
What exactly am i doing wrong? It always selects the same number of records regardless of me adding or removing recycleLogs
I've managed to get it done through a raw SQL query which i'll post below in case it helps anyone, i'd still like to know how to do it in Eloquent/Query Builder.
SELECT * FROM `leads` LEFT JOIN `lead_recycling_logs` ON `leads`.`guid` = `lead_recycling_logs`.`original_lead_guid` WHERE `leads`.`campaign_id` = :campaignID AND `leads`.`duplicated` = 0 AND `leads`.`lead_status` != :invalidStatus AND (`lead_recycling_logs`.`id` IS NULL OR `lead_recycling_logs`.`created_at` < :recyclingDate) ORDER BY `leads`.`created_at` DESC
Try this:
$leads = $this->leadModel->where(Lead::CAMPAIGN_ID, $this->campaignID)
->where(Lead::DUPLICATED, Lead::DUPLICATED_NO)
->where(Lead::LEAD_STATUS, "!=" ,Lead::LEAD_STATUS_INVALID)
->orderBy(Lead::CREATED_AT, 'desc')
->where(function($q) {
$q->whereHas('leadRecyclingLog', function($q) {
$q->where(LeadRecyclingLog::CREATED_AT, '<', (new Carbon())->subDays($this->configRecyclingDays));
})
->orWhereHas('leadRecyclingLog', '<', 1); // Where count of the relationship is smaller than 1
})->get();
I assumed the first part of the query is working well (up until the relationship).
What you're looking for is ->whereHas(relationship), not ->with(relationship). ->with(relationship) will attach the associated results to the original model (the query for the original model will not be affected by ->with()). ->whereHas(relationship) filters the original model by the condition.
Got it to work through #devk 's help
$leads = $this->leadModel->where(Lead::CAMPAIGN_ID, $this->campaignID)
->where(Lead::DUPLICATED, Lead::DUPLICATED_NO)
->where(Lead::LEAD_STATUS, "!=" ,Lead::LEAD_STATUS_INVALID)
->orderBy(Lead::CREATED_AT, 'desc')
->where(function($q) {
$q->whereHas('leadRecyclingLog', function($q) {
$q->where(LeadRecyclingLog::CREATED_AT, '<', (new Carbon())->subDays($this->configRecyclingDays));
})
->doesntHave('leadRecyclingLog', 'or');
})->get();

Resources