Hello There!
I want to get only the rows where the punch_in_time is greater than the expected_punch_in_time (You can see the columns in the picture link above).
I searched a lot and I did not found anything helpful, I tried the "whereDate" method but it turns out that it only works on datetime fields and not only time as in my case.
Any help would be appreciated!
Thank you.
You can use whereTime function in querybuilder
whereTime('punch_in_time', '>', 'expected_punch_in_time')
for more details refer link https://laravel.com/docs/9.x/queries
Use eloquent: whereTime (colum, '>' colum);
Or if want pure SQL u can use this:
SELECT * FROM testTime WHERE
CAST(punch_in_time AS TIME) > CAST(expected_punch_in_time AS TIME);
SELECT * FROM testTime WHERE
punch_in_time > expected_punch_in_time;
fiddle here
Finally, I figured it out, I have used the "whereColumn" method and it worked well.
public function ScopeLateDrivers($query)
{
return $query->whereColumn('punch_in_time', '>', 'expected_punch_in_time');
}
Related
I want to write this raw query using Eloquent. I have tried using ->whereRaw but it shows error due to special characters in it.
SELECT id,shipping_email FROM orders WHERE 1 AND `shipping_email` NOT REGEXP '^[A-Z0-9._%-]+#[A-Z0-9.-]+\.[A-Z]{2,63}$' AND id = '<>'
Help is appreciated...
Thanks in advance.
I have got answer, I have tried these codes..
\Model\Order::query()
->select('id', 'shipping_email')
->whereRaw("`shipping_email` NOT REGEXP ?", ["^[A-Z0-9._%-]+#[A-Z0-9.-]+\.[A-Z]{2,63}$"])
->get();
I have two columns in my table: max and current. I want to build simple scope
public function scopeNotMax($query)
{
return $query->where('max', '>', 'current');
}
But Laravel gives me that query:
SELECT * FROM table WHERE `max` > 'current'
I don't want this result and I know that I can use in this place whereRaw() or DB::raw(). But I can't find another way to say "hey, this is column, not string!'. Can I do it? Or I must use raws? I want to avoid it.
There is no other way.
where() method in this case add third parameter (value) to bindings and passes it ot PDO library. So it will be escaped.
Alternatively You can pass as third parameter a Closure, but then laravel will form a sub-select for You, which doesn't helps much.
Looks like whereRaw() is made for this kind of sitiuation.
Did you give a try with this ? return $query->where('max > current');
you can use whereRaw():
->whereRaw('table_1.name = table_2.name');
You exmaple code:
->whereRaw('max>current');
I have table of dogs in my DB and I want to retrieve N latest added dogs.
Only way that I found is something like this:
Dogs:all()->where(time, <=, another_time);
Is there another way how to do it? For example something like this Dogs:latest(5);
Thank you very much for any help :)
You may try something like this:
$dogs = Dogs::orderBy('id', 'desc')->take(5)->get();
Use orderBy with Descending order and take the first n numbers of records.
Update (Since the latest method has been added):
$dogs = Dogs::latest()->take(5)->get();
My solution for cleanliness is:
Dogs::latest()->take(5)->get();
It's the same as other answers, just with using built-in methods to handle common practices.
Dogs::orderBy('created_at','desc')->take(5)->get();
You can pass a negative integer n to take the last n elements.
Dogs::all()->take(-5)
This is good because you don't use orderBy which is bad when you have a big table.
You may also try like this:
$recentPost = Article::orderBy('id', 'desc')->limit(5)->get();
It's working fine for me in Laravel 5.6
I use it this way, as I find it cleaner:
$covidUpdate = COVIDUpdate::latest()->take(25)->get();
Ive come up with a solution that helps me achieve the same result using the array_slice() method. In my code I did array_slice( PickupResults::where('playerID', $this->getPlayerID())->get()->toArray(), -5 ); with -5 I wanted the last 5 results of the query.
The Alpha's solution is very elegant, however sometimes you need to re-sort (ascending order) the results in the database using SQL (to avoid in-memory sorting at the collection level), and an SQL subquery is a good way to achieve this.
It would be nice if Laravel was smart enough to recognise we want to create a subquery if we use the following ideal code...
$dogs = Dogs::orderByDesc('id')->take(5)->orderBy('id')->get();
...but this gets compiled to a single SQL query with conflicting ORDER BY clauses instead of the subquery that is required in this situation.
Creating a subquery in Laravel is unfortunately not simply as easy as the following pseudo-code that would be really nice to use...
$dogs = DB::subQuery(
Dogs::orderByDesc('id')->take(5)
)->orderBy('id');
...but the same result can be achieved using the following code:
$dogs = DB::table('id')->select('*')->fromSub(
Dogs::orderByDesc('id')->take(5)->toBase(),
'sq'
)->orderBy('id');
This generates the required SELECT * FROM (...) AS sq ... sql subquery construct, and the code is reasonably clean in terms of readability.)
Take particular note of the use of the ->toBase() function - which is required because fromSub() doesn't like to work with Eloquent model Eloquent\Builder instances, but seems to require a Query\Builder instance). (See: https://github.com/laravel/framework/issues/35631)
I hope this helps someone else, since I just spent a couple of hours researching how to achieve this myself. (I had a complex SQL query builder expression that needed to be limited to the last few rows in certain situations).
For getting last entry from DB
$variable= Model::orderBy('id', 'DESC')->limit(1)->get();
Imagine a situation where you want to get the latest record of data from the request header that was just inserted into the database:
$noOfFilesUploaded = count( $request->pic );// e.g 4
$model = new Model;
$model->latest()->take($noOfFilesUploaded);
This way your take() helper function gets the number of array data that was just sent via the request.
You can get only ids like so:
$model->latest()->take($noOfFilesUploaded)->puck('id')
use DB;
$dogs = DB::select(DB::raw("SELECT * FROM (SELECT * FROM dogs ORDER BY id DESC LIMIT 10) Var1 ORDER BY id ASC"));
Dogs::latest()->take(1)->first();
this code return the latest record in the collection
Can use this latest():
$dogs = Dogs::latest()->take(5)->get();
I am trying to combine Where And OR in Codeigniter via code.
$this->db->where("id",1);
$this->db->where("status","live")->or_where("status","dead");
Appeared result is as query
where id=1 and status='live' OR status='dead'
Whereas i need result for this query.
where id=1 and (status='live' OR status='dead');
NOTE: Please don't give solution of string passed as parameter from where function. That's not fit into my code. I Just simplified my problem above.
Just found solution, if it can help some one.
$this->db->where("id",1)->where("(status='live' OR status='dead')");
you can use where_in() like this
$status_array = array('live','dead');
$this->db->where("id",1);
$this->db->where_in('status', $status_array);
you just add ->group_start() and ->group_end()
$this->db->where("id",1);
$this->db->where("status","live")
->group_start()
->or_where("status","dead")
->group_end();
I heed two variables storing the maximum id from a table, and the minimum id from the same table.
the first id is easy to be taken ,using find() and a query like
$first = Model::factory('product')->sale($sale_id)->find();
but how can i retrieve the last id? is there a sorting option in the Kohana 3 ORM?
thanks!
Yes, you can sort resulting rows in ORM with order_by($column, $order). For example, ->order_by('id', 'ASC').
Use QBuilder to get a specific values:
public function get_minmax()
{
return DB::select(array('MAX("id")', 'max_id'),array('MIN("id")', 'min_id'))
->from($this->_table_name)
->execute($this->_db);
}
The problem could actually be that you are setting order_by after find_all. You should put it before. People do tend to put it last.
This way it works.
$smthn = ORM::factory('smthn')
->where('something', '=', something)
->order_by('id', 'desc')
->find_all();
Doing like this, I suppose you'll be :
selecting all lines of your table that correspond to your condition
fetching all those lines from MySQL to PHP
to, finally, only work with one of those lines
Ideally, you should be doing an SQL query that uses the MAX() or the MIN() function -- a bit like this :
select max(your_column) as max_value
from your_table
where ...
Not sure how to do that with Kohana, but this topic on its forum looks interesting.