how to make query with substr in eloquent (laravel 4)? - laravel

I have this query:
select substr(id,1,4) as id
from meteo.a2012
group by substr(id,1,4)
I just want to take first 4 numbers to my id row, but I'm trying to do in eloquent, how I do?
Thanks.

You need to use raw expressions so you can use special functions like that.
Model::select(DB::raw('substr(id, 1, 4) as id'))->groupBy(DB::raw('substr(id, 1, 4)'))->get();
Where Model is your Eloquent model you want to run the query on.

G'day
I was able to do it like this in Laravel
$data = DataModel::selectRaw("SUBSTRING_INDEX(EMAIL_COLUMN, '#', 1) as 'alias'")->get();
As a result, I get the alias name (address) from the mail address#domain.net

$ids = Model::get(['id']);
foreach ($ids as $str)
{
$str->id =substr($str->id,1,4);
}
return $ids;

Related

How to select min and max in laravel

I want to convert this code in laravel.
SELECT MAX(date_start) AS DateStart,MIN(date_end) AS DateEnd FROM DBTest
And I try this code
$data = DB::table('DBTest')
->select(max('date_start'), min('date_end')))
->get();
Return Error: max(): When only one parameter is given, it must be an array
I am using laravel 5.2, and SQLyog as database
I am confuse in syntax please help me
You can't use functions in select statement, but you can use raw SQL :
$data = DB::table('DBTest')
->select(\DB::raw('MIN(date_start) AS DateStart, MAX(date_end) AS DateEnd'));
->get();
You can do it like this:
For the max start date:
max = DB::table('DBTest')->select('date_start')->orderBy('date_start', 'desc')->first();
For min end date:
min = DB::table('DBTest')->select('date_end')->orderBy('date_end', 'asc')->first();
You have to use something called selectRaw method in Laravel in order to achieve this result. Chaining method like ->max('columnA')->min('columnB') will not work. So, here is the solution:
$data = DB::table('DBTest')
->selectRaw('MAX(date_start) AS DateStart, MIN(date_end) AS DateEnd')->get();
Try MIN() and MAX() functions in the sql query.
$data = DB::table('DBTest')
->select(\DB::raw('MIN(date_start) AS startDate, MAX(date_end) AS endDate'));
->get();

Laravel Model::find() auto sort the results by id, how to stop this?

$projects = Project::find(collect(request()->get('projects'))->pluck('id')); // collect(...)->pluck('id') is [2, 1]
$projects->pluck('id'); // [1, 2]
I want the result to be in the original order. How do I achieve this?
Try $projects->order_by("updated_at")->pluck("id"); or "created_at" if that's the column you need them ordered by.
Referencing MySQL order by field in Eloquent and MySQL - SELECT ... WHERE id IN (..) - correct order You can pretty much get the result and have it order using the following:
$projects_ids = request()->get('projects'); //assuming this is an array
$projects = Project::orderByRaw("FIELD(id, ".implode(',', projects_ids).")")
->find(projects_ids)
->pluck('id'));
#Jonas raised my awareness to a potential sql injection vulnerability, so I suggest an alternative:
$projects_ids = request()->get('projects');
$items = collect($projects_ids);
$fields = $items->map(function ($ids){
return '?';
})->implode(',');
$projects = Project::orderbyRaw("FIELD (id, ".$fields.")", $items->prepend('id'))
->find($projects_ids);
The explanation to the above is this:
Create a comma separated placeholder '?', for the number of items in the array to serve as named binding (including the column 'id').
I solve this by querying the data one by one instead mass query.
$ids = collect(request()->get('projects'))->pluck('id');
foreach($ids as $id){
$projects[] = Project::find($id);
}
$projects = collect($projects);
$projects->pluck('id');
I have to do this manually because laravel collection maps all the element sorted by using ids.

Codeigniter Query binding multiple fields with the same value

I'm in a situation where I'm doing a MySQL query with Codeigniter and where I have a lot of fields value request which are ALL the same.
Example:
$this->db->query('SELECT * FROM abc WHERE user_id = ? AND msg_from = ? AND msg_to != ?', [$id, $id, $id]);
This has just 3 question marks but the query I'm working on is HUGE and has 19 question marks WHICH ARE ALL THE SAME variable.
So I was trying to figure out how to tell Codeigniter all question marks are pointing to the same variable without having to fill an array with 19 times the same variable.
I thought of a for-loop but I wanted to know if a shortcut exist.
you should be able to do this with Codeigniters Query Builder pretty easily
Something like that should work:
$this->db
->select('*')
->from('abc');
$arrFields = array('users_id', 'msg_from', 'msg_to');
foreach($arrFields AS $val)
{
$this->db->where($val, $id);
}
$query = $this->db->get();

What is the equivalent query of laravel on this?

This is the native sql:
$sql = "Select count(name) from users Where email = 't#t.com' and user_id = 10";
I have this laravel code:
$checker = Customer::whereEmailAndUserId("t#t.com",10)->count("name");
Is this a correct way to do it in laravel?
You have to use where helper function and pass an array of checks. For example in your code it will be:
$checker = Customer::where([
['email', '=', 't#t.com'],
['user_id' '=', '10']
])->count();
Note: Please use the appropriate column name as it in table.
Assuming Customer model represents table users, you'll get query with eloquent like this:
Customer::where('email', 't#t.com')->where('user_id', 10)->select(\DB::raw('count(name)'))->get();
The option you are trying is incorrect
here is the right option
$users = \App\Customer::where('email','t#t.com')
->where('user_id',10)
->count()
Explanation of above code
App\Customer is the Model class and I am trying to read records where email = 't#t.com you can use various comparison operators like <,> and so on and you can also use the same function to for string pattern matching also
Eg.
$users = \App\Customer::where('email','%t.com')
->where('user_id',10)
->count()
You can use the same where function for Null Value test also
Eg.
$users = \App\Customer::where('email','=', null)
->where('user_id',10)
->count()
The above where clause will be converted to is null test of the SQL
You can read more here

Laravel WhereIn or Wheren with where

Im trying to design a query, but I have no idea where to start.
I'll type it out how I want it to function.
Items::whereIn('id',$ids)->orWhereIn('id_2',$ids)->where('type','!=',$type)->get();
Thats how I want it to work, but I know that wont work, because it will just ignore the WHERE type=$type query, because the whereIN's would have already pulled records, that dont adhere to the Where query.
Basically I want the eloquent version of this...
"SELECT * FROM items WHERE type!=$type AND (id IN (1,2,3) OR id_2 IN(1,2,3))"
What you are attempting to do is to group statements: https://laravel.com/docs/5.3/queries#parameter-grouping
What you need to do is to make the code something like this:
Items::where('type', '!=', $type)
->where(function ($query) use ($ids) {
$query->whereIn('id',$ids)
->orWhereIn('id_2',$ids);
})
->get();
That way you are grouping the where in clauses.
$user_id = 2 ;
$user_ids = [2,3,4,5,6,7,78,87,88,90] ;
where('id',$user_id) vs whereIn('id',$user_ids)
Note: where will compare with just first value of array or just one single value. and whereIn will compare evey index of array.
You're gonna want to do something like this:
Item::where('type','!=','ATypeTest')->where(function ($query) {
$query->whereIn('id',[1, 2, 3])->orWhereIn('id_2',[1, 2, 3]);
})->get();
Check the Laravel documentation on more regarding grouping: https://laravel.com/docs/5.3/queries#parameter-grouping
This will by the way generate the following SQL query:
SELECT * FROM "items" WHERE "type" != `ATypeTest` AND ("id" in (1, 2, 3) OR "id_2" in (1, 2, 3))

Resources