Using two columns in where Laravel ORM - php

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

Related

Laravel Eloquent return count of each group with groupBy()

I want to groupBy() task using Laravel Eloquent. I have searched Internet and didn't find anything with eloquent.
some people used groupBy() query with Query Builder like this link
But I want to create query like this style:
Task::select('id')->groupBy('category_id')->count();
This code just return only count of first category_id. But I want count of all the category_id.
Native Collection alternative (grouped by php, not mysql). It's a nice option when you have the Collection as variable already assigned. Of course is less optimal than mysql grouping in most cases.
$tasks->groupBy('category_id')->map->count();
You should add the count to the select function and use the get function to execute the query.
Task::select('id', \DB::raw("count(id)"))->groupBy('category_id')->get();
The \DB::raw() function makes sure the string is inserted in the query without Laravel modifying its value.
More simple:
Task::select('id')->groupBy('category_id')**->get()**->count();
You can do something like this:
return DB::table('offers')->select('*', DB::raw('count('.$field.') as total_count'))->groupBy($field)->get();
I overrode the count() method in my model. Could be something like:
public function count($string = '*'){
$tempmodel = new YourModel();
return $tempmodel ->where('id',$this->id)->where('category_id',$this->category_id)->count($string);
}
This gave me exactly the behavior of count() I was looking for.
Worked for me as
we need to select one column like 'category_id' or 'user_id' and then
count the selected column on get()
Task::select('category_id')
->where('user_id',Auth::user()->id)
->groupBy(['category_id'])
->get()
->count();
This works for me.
output:
return $email_trackers = EmailTracker::get()->groupBy('campaign_id')->map->count();
{
"6": 2
}

How to use substr() inside an orderBy function in Laravel

Good day,
I need to sort my result by using "orderBy" function in laravel but unfortunately the values in that column that I want to use has "j1_" before the actual number.. so I want to remove the first 3 character first but when I tried
orderBy(substr('x_fs_format_details.tree_xid', 3))
it gives me a "Column not found" error.
Is there a way to tweak this? thanks.
I'm assuming you use MYSQL (the substring function might be different on other databases)
You can either make a new field on the fly:
$query->selectRaw('*, SUBSTR(x_fs_format_details.tree_xid, 3) AS substr_tree_xid')
->orderBy('substr_tree_xid')->get();
This has the advantage/disadvantage that the result of SUBSTR will be in your result. If you don't want that you can also use SUBSTR in the order by directly:
$query->orderByRaw('SUBSTR(x_fs_format_details.tree_xid, 3)')->get();

Laravel: How to get last N entries from DB

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

Kohana orm order asc/desc?

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.

Doctrine: How can I have a where clause included only when necessary in a query?

I want to use a single query to retrieve:
items of any categories (no filter applied);
only items of a single category (limited to a particular category);
For that purpose I should be able to write a Doctrine query which would include a where clause only when certain condition is met (eg. part of URL existing), otherwise, where clause is not included in the query.
Of course, i tried with using the If statement, but since doctrine query is chained, the error is thrown.
So i guess the solution might be some (to me unknown) way of writing doctrine queries in an unchained form (by not having each row started with "->" and also having each row of a query ending with semicolon ";")
That way the usage of IF statement would be possible i guess.
Or, maybe there's already some extremely simple solution to this matter?
Thanks for your reply!
I am unfamiliar with Codeigniter but can't you write something like this?
$q = Doctrine_Query::create()
->from('items');
if ($cat)
$q->where('category = ?', $cat);
In your model pass the condition for where as a parameter in a function.
In below example i am assuming the function name to be filter_query() and passing where condition as a parameter.
function filter_query($condition=''){
$this->db->select('*');
$this->db->from('TABLE NAME');
if($condition != ''){
$this->db->where('condition',$condition);
}
}
In above example i have used Codeigniter's Active Record Class.

Categories