Laravel 4.2 - can't get random rows from database - laravel-4

Can someone explain to me why this works
$profile = Profile::all()->random(8);
and this doesn't work
$profile = Profile::where('gender_id', '=', 1)->random(8);
I get the error saying
Call to undefined method Illuminate\Database\Query\Builder::random()

You should use:
$profile = Profile::where('gender_id', '=', 1)->get()->random(8);
Because random() function gets random items from collection. Reference

Add ->get()
$profile = Profile::where('gender_id', '=', 1)->get()->random(8);

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();

Wildcard-like syntax in an eloquent Where clause to search between two strings

I saw the answer provided in this question Wildcard-like syntax in an eloquent Where clause? now I want to know if is there a way to search between two strings?.
basicasicaly in my code I want to show requests that have a status of new or scheduled.
$requests = DB::table('requests')
->select('requestDate','requestTime','status','requestID')
->where('requestorID', '=',$userID)
->where('status', 'LIKE','%New%')
->get();
you can use whereIn ,The whereIn method verifies that a given column's value is contained within the given array:
$requests = DB::table('requests')
->select('requestDate','requestTime','status','requestID')
->where('requestorID', '=',$userID)
->whereIn('status', ['new','scheduled'])
->get();
You can use:
->where('status', 'new')
->orWhere('status', 'scheduled')
you can simply use a where with an orWhere:
$requests = DB::table('requests')
->select('requestDate','requestTime','status','requestID')
->where('requestorID', '=',$userID)
->where(function($q) {
$q->where('status', 'LIKE','%New%');
$q->orWhere('status', 'LIKE','%Scheduled%');
})->get();

How to make aritmetic operations from latest record to the previous one in Laravel

I acomplished this when user make input like this:
$CalcPrevNumb = model::latest()->first();
$student = new model([
'recordtime' => $request->get('recordtime'),
'obem_sprqmo_pr_den' => $request->get('cname2') - $CalcPrevDay->cname2
]);
$student->save();
But now the goal is to do this when for example csv file is imported in to the DB(pgsql). Now I need to substract the last created and the previous one.
Something like this?
$CalcPrevNumb = model::latest()->first(); // not the latest but previous
$students = model::whereBetween('recordtime', $dateScope)
->selectRaw('recordtime, cname2 - $CalcPrevNumb')
->orderBy('recordtime', 'ASC')
->get();
How to do this in Elequent?
You may use the skip and take methods to limit the number of results returned from the query or to skip a given number of results in the query
Official Doc
Working solution:
// create object for the prev day
$user = model::whereBetween('recordtime',$dateScope)->selectRaw('recordtime')->first();
// if no records for current day don't brake the code
if($user === Null){
$user = model::latest('recordtime')->first();
}
$CalcPrevDay = model::where('recordtime', '<', $user->recordtime)
->latest('recordtime')
->first();
$students = model::whereBetween('recordtime', $dateScope)
->selectRaw('recordtime, (cname2 - ?) as obem_sprqmo_pr_den', [$CalcPrevDay->obem_m3])
->orderBy('recordtime', 'ASC')
->get();
I tryed:
$students = model::whereBetween('recordtime', $dateScope)
->selectRaw('recordtime, (cname2 - :CalcPrevDay) as obem_sprqmo_pr_den', array('CalcPrevDay'=>$CalcPrevDay->cname2))
->orderBy('recordtime', 'ASC')
->get();
But error occurred:
SQLSTATE[HY093]: Invalid parameter number: mixed named and positional parameters
Can't understand why but stick to my first solution. If someone have better solution will wait for it.

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!

Laravel using paginate() with select() method

Is it possible to use paginate() with the select() method? Using the code below I get the error:
Call to a member function paginate() on a non-object
$query = 'SELECT * FROM items';
$results = DB::select($query)->paginate(10);
I know the following code works with paginate() with just the table() method:
$results = DB::table('plans_shared')->paginate(10);
It seems much easier for me to use the select() since I have many conditional AND/WHERE clauses
select() method returns array so paginate() cannot be called on it. You can only try to use \Paginator::make(DB::select($query)) if you like
If you have an array and want to paginate it use Paginate::make() Paginate Laravel 4.2
Ex:
$pages = Paginate::make(DB::select($query), 10);
$items = DB::table('team')
->selectRaw('SELECT *,earth_distance(ll_to_earth(team.lat, team.lng), ll_to_earth(23.1215939329,113.3096030895)) AS distance')
->whereRaw('earth_box(ll_to_earth(23.1215939329,113.3096030895),1000) #> ll_to_earth(team.lat, team.lng)')
->paginate(10);

Resources