I'm new to laravel and i am wanting to use multiple where clauses and use curdate().
This is an example :
$data = DB::table('toutcome')->where('date', '>=', curdate())->where('Status', '=', 'A')->count('AppID');
return view('home', compact('data'));
It's not working at all.
So along with the answers in the comments:
public function index()
{
// First query with DB::raw() variant
$data = DB::table('toutcome')
->where('date', '>=', DB::raw('curdate()'))
->where('Status', '=', 'A')
->count('AppID');
// Second query with Carbon variant
$data2 = DB::table('toutcome')
->where('date', '>=', Carbon::now())
->where('Status', '=', 'A')
->count('AppID');
// Third query with '#Sunny' whereRaw variant
$data3 = DB::table('toutcome')
->whereRaw('date >= curdate()')
->where('Status', '=', 'A')
->count('AppID');
return view('home', compact('data','data2','data3'));
}
I'm not a big fan of compact() personally so I would write:
return view('home', ['data'=>&$data,'data2'=>&$data2,'data3'=>&$data3])
although personally (if you want to read on taking it further) read up on ViewComposers:
https://laravel.com/docs/master/views#view-composers
Change
where('date', '>=', curdate())
to
whereRaw('date >= curdate()')
Related
I need a little help regarding the syntax of Eloquent. I want to add more where clauses but can't get the OR working. I read https://laravel.com/docs/7.x/queries#where-clauses but my statement fails.
Works:
$events = DB::table('events')->select('id','resourceId','title','start','end')
->whereDate('start', '>=', $start)->whereDate('end', '<=', $end)->get();
Does not work:
$events = DB::table('events')->select('id','resourceId','title','start','end')
->whereDate('start', '>=', $start)->whereDate('end', '<=', $end)
->orWhere(function($query) {
$query->whereDate('start', '<=', $start)
->whereDate('end', '>=', $end);
})
->get();
Is orWhere not supposed to work with whereDate?
First; while using closures you need to pass arguments with use. You may or two main conditions and in their nested conditions both sub-conditions will be anded.
public function index()
{
DB::table('events')
->select('id', 'resourceId', 'title', 'start', 'end')
->where(function ($query) use ($start, $end) {
$query->whereDate('start', '>=', $start)->whereDate('end', '<=', $end);
})
->orWhere(function ($query) use ($start, $end) {
$query->whereDate('start', '<=', $start)->whereDate('end', '>=', $end);
})
->get();
}
This function will print (don't mind about the dates, just example)
SELECT `id`, `resourceId`, `title`, `start`, `end`
FROM `events`
WHERE (date(`start`) >= '2020-06-15' and date(`end`) <= '2020-06-16')
or (date(`start`) <= '2020-06-15' and date(`end`) >= '2020-06-16')
Good day all, I am trying to count all records in a table but only if the table does not contain data in a specific column (deleted_at). It is a join table the table names are companies and employees. I am currently counting the records with a DB::raw but it should only count it if the deleted_at column is null. Please understand that i am a beginner.
public function index()
{
$user = Auth::user()->id;
$companies = DB::table('companies AS c')
->select([
'c.id',
'c.logo',
'c.company_name',
'c.created_at',
'c.sector',
'c.deleted_at',
DB::raw('COUNT(e.id) AS employee_count')
])
->leftJoin('employees AS e', 'e.company_id', '=', 'c.id' )
->leftJoin('company_user AS cu', 'cu.company_id', '=', 'c.id')
->where('cu.user_id', '=', $user)
->where('c.deleted_at', '=', null)
->groupBy('c.id')
->get();
return view('account.companies.index')
->with('companies', $companies);
}
If you are using Mysql then you could use conditional aggregation
$companies = DB::table('companies AS c')
->select([
'c.id',
'c.logo',
'c.company_name',
'c.created_at',
'c.sector',
'c.deleted_at',
DB::raw('SUM(c.deleted_at IS NULL) AS employee_count')
])
->leftJoin('employees AS e', 'e.company_id', '=', 'c.id' )
->leftJoin('company_user AS cu', 'cu.company_id', '=', 'c.id')
->where('cu.user_id', '=', $user)
->groupBy('c.id')
->get();
In mysql when an expression is used inside sum(a= b) it will result as a boolean 0/1 so you can get your conditional count using above
Or you could use whereNull() method in your query
->whereNull('c.deleted_at')
Use this code:
$employeeCount = DB::table('employees')
->select('companies.name', DB::raw('count(employees.id) as employee_count'))
->join('companies', 'employees.company','=','companies.id')
->groupBy('companies.id')
->get();
How can I use AS in my count query?
Actually i want to result like { "count":"number" } for json result. I dont know what should i call this thing?
public function firstHourTrades(){
$user_id = Auth::user()->id;
$data = DB::table('finaltrade')
->join('exchanges', 'finaltrade.exchange_id', '=', 'exchanges.id')
->where('finaltrade.user_id', $user_id)
->whereTime(DB::raw('IF(finaltrade.buy_datetime<finaltrade.sell_datetime, finaltrade.buy_datetime, finaltrade.sell_datetime) '), '>=', DB::raw('exchanges.start_time'))
->whereTime(DB::raw('IF(finaltrade.buy_datetime<finaltrade.sell_datetime, finaltrade.buy_datetime, finaltrade.sell_datetime) '), '<=', DB::raw("ADDTIME(exchanges.start_time, '1:00:00')"))
->count();
return response()->json($data);
}
You could also do a raw select and manually assign the alias:
$data = DB::table('finaltrade')
->select(DB::raw('count(*) as count'))
->join('exchanges', 'finaltrade.exchange_id', '=', 'exchanges.id')
->where('finaltrade.user_id', $user_id)
->whereTime(DB::raw('IF(finaltrade.buy_datetime<finaltrade.sell_datetime, finaltrade.buy_datetime, finaltrade.sell_datetime) '), '>=', DB::raw('exchanges.start_time'))
->whereTime(DB::raw('IF(finaltrade.buy_datetime<finaltrade.sell_datetime, finaltrade.buy_datetime, finaltrade.sell_datetime) '), '<=', DB::raw("ADDTIME(exchanges.start_time, '1:00:00')"))
->get();
I have a page that connects to my database, but it takes about 1 minute for the page to load after collecting all the data.
Is there something I am doing wrong, or is there something I can do to speed this process up?
Controller
class ReportSummaryController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function __construct()
{
$this->middleware('auth');
$user = Auth::user();
if (#$user->name)
$details = DB::table('taffiliate')
->where('affID', "=", $user->name)
->get();
else
return redirect('/login');
view()->share('details', $details);
}
public function index()
{
$user = Auth::user();
$affiliate = $user->name;
$affdata = DB::table('toutcome')->select(DB::raw('sum(LenderCommission) as LenderCommission'), 'AffID', 'AppID')
->whereRaw('CompletedDate >= curdate()')
->groupBy('AffID')
->orderBy('AppID', 'ASC')
->get();
$data3 = DB::table('toutcome')
->where('CompletedDate', '>=', \Carbon\Carbon::now()->startOfMonth())
->whereRaw('AffID Not Like "MW0050"')
->join('tapplicant', 'toutcome.AppID', '=', 'tapplicant.AppID')
->select(DB::raw('DATE_FORMAT(CompletedDate, "%d %M %Y") as CompletedDate,
SUM(LenderCommission) as commission,
SUM(AffCommission) as affCommission,
COUNT(DISTINCT tapplicant.Email) as leadcount,
SUM(Status = "A" AND LenderCommission Not Like "0.00") as acceptcount'))
->groupBy(DB::raw('DATE_FORMAT(CompletedDate, "%d %M %Y")'))
->get();
$users = Toutcome::where('CompletedDate', '>=', \Carbon\Carbon::now()->startOfMonth())
->join('tapplicant', 'toutcome.AppID', '=', 'tapplicant.AppID')
->select(DB::raw('DATE_FORMAT(CompletedDate, "%d %M %Y") as CompletedDate,
SUM(LenderCommission) as Commission,
SUM(AffCommission) as Affiliate_Commission,
COUNT(DISTINCT tapplicant.Email) as Applications,
SUM(Status = "A" AND LenderCommission Not Like "0.00") as Sold'))
->whereRaw('AffID Not Like "MW0050"')
->groupBy(DB::raw('DATE_FORMAT(CompletedDate, "%d %M %Y")'))
->get();
$comtotal = DB::table('toutcome')
->where('CompletedDate', '>=', \Carbon\Carbon::now()->startOfMonth())
->whereRaw('LenderCommission Not Like "0.00"')
->sum('LenderCommission');
$subid = DB::table('tapplicant')
->whereRaw('AppAffID Not Like "050"')
->whereRaw('AppAffID Not Like "000"')
->where('AppDate', '>=', \Carbon\Carbon::now()->startOfMonth())
->select('AppAffID')
->groupBy('AppAffID')
->get();
$lender = DB::table('toutcome')
->select('LenderName')
->groupBy('LenderName')
->get();
$imtotal = DB::table('toutcome')
->where('CompletedDate', '>=', \Carbon\Carbon::now()->startOfMonth())
->whereRaw('LenderCommission Not Like "0.00"')
->whereRaw('AffID Not Like "0050"')
->count('AppID');
$cototal = DB::table('toutcome')
->where('CompletedDate', '>=', \Carbon\Carbon::now()->startOfMonth())
->whereRaw('LenderCommission Not Like "0.00"')
->whereRaw('AffID Not Like "0050"')
->where('Status', '=', 'A')
->count('AppID');
$comtotal2 = DB::table('toutcome')
->where('CompletedDate', '>=', \Carbon\Carbon::now()->startOfMonth())
->whereRaw('LenderCommission Not Like "0.00"')
->sum('LenderCommission');
$comtotal3 = DB::table('toutcome')
->where('CompletedDate', '>=', \Carbon\Carbon::now()->startOfMonth())
->whereRaw('LenderCommission Not Like "0.00"')
->sum('AffCommission');
return view('summary', compact('affdata','data3', 'comtotal', 'subid' , 'users', 'lender', 'imtotal', 'cototal', 'comtotal2', 'comtotal3'));
}
Firstly that sounds really long.
The queries do look quite detailed, but it shouldn't take longer than 1 minute.
You could try using eloquent, but this will be only a little quicker than the raw queries.
Things you didn't mention are :
Is this a local server or remote server ?
If you are using a remote server, my solution would be to use the "skip-name-resolve" in your my.ini / my.cnf under mysqld and update your key_buffer_size.
If this does not improve the speed, maybe look at your resources for that particular server.
What i'm trying to achieve is the following:
I want to check if there is a record with the same client_code but with a lower/different campaign id. I'm using a sub-query for now and i tried to do it with a join as well but I couldn't get the logic working
This is what i got now:
$oDB = DB::table('campaigns AS c')
->select(
'c.id AS campaign_id',
'cc.id AS campaign_customer_id'
)
->join('campaign_customers AS cc', 'cc.campaign_id', '=', 'c.id')
->where('c.status', '=', ModelCampaign::STATUS_PLANNED)
->where('c.scheduled', '=', 1)
->whereRaw('c.scheduled_at <= NOW()')
->where('cc.status', '=', ModelCampaignCustomer::STATUS_INVITE_EMAIL_SCHEDULED)
->whereNotIn('cc.client_code', '=', function ($query){
$query ->select(DB::raw(1))
->from('campaign_customers')
->whereRaw('campaign_id', '!=', 'c.id');
})
->where('cc.active', '=', 1)
;
any tips on how to work the logic would be great
You can use the ->toSql(); method to see the SQL so you can refactorize your query.
The whereNotIn probably shouldn't have an = in it
->whereNotIn('cc.client_code', function ($query){
....
edit
Try:
->whereNotIn('cc.client_code', function ($query){
$query->select(DB::raw('client_code'))
->from('campaign_customers')
->whereRaw('campaign_id != c.id');
})
I think the whereRaw should be a single text string or maybe you can use where here (looking at this for reference https://laravel.com/docs/5.2/queries#advanced-where-clauses). Also DB::raw(1) is going to return a 1 for each subquery result but you want an id for the whereNotIn.