Kohana Database Query Builder custom sort order ("ORDER BY Field (id, 1, 3, 2)" in MySQL) - sql-order-by

I have a set of id's to select, so I request:
$ids = array( 1, 2, 3, 4, 5 );
$q = DB::select('field1', 'field2', 'field3')->
from('work')->
where('field1', 'in', $ids)->execute();
How can I sort them in my custom order, like MySQL's 'ORDER BY Field' do?

Check out DB::Expr
You can use it like so:
->order_by(DB::Expr('FIELD(`field`, 3,1,2)'))
Note, you'll have to manually escape the contents

Related

Laravel distinct users by gender and count

I am wondering how I can count the number of males/females/na users in my database, using Laravel Eloquent model.
I want this to happen in one query and to receive the following array:
[
['male' => 3],
['female' => 4],
['na' => 5],
]
Something like that:
$users->pluck('gender', 'count(*)')->unique();
You can try this :
$q = User::select('gender', DB::raw('count(*) as total'))
->groupBy('gender')
->get();

Laravel collection->diff() not working when using select

I have table where I want to find difference in certain columns. I'm doing it with diff():
$inventoryitems1 = InventoryItem::where('inventory_id', $request->get('inventory1'))
->select('owner_id', 'location_id', 'asset_id')
->get();
$inventoryitems2 = InventoryItem::where('inventory_id', $request->get('inventory2'))
->select('owner_id', 'location_id', 'asset_id')
->get();
$difference = $inventoryitems2->diff($inventoryitems1);
And then i get empty array. But if I don't have select in my collection. It work, it shows all different rows. Is there anyother way to do this or this one is right but I'm not doing it the right way?
UPDATE
I have $inventoryitems1 collection that looks like this:
0: {asset_id: 2, owner_id: 2, location_id: 1}
1: {asset_id: 3, owner_id: 2, location_id: 1}
and $inventoryitems1 collection that looks like this:
0: {asset_id: 2, owner_id: 2, location_id: 1}
1: {asset_id: 3, owner_id: 6, location_id: 1}
I'm trying to find differences in those two collections, where we can see that owner_id is different in second collection. How can I only get those objects where there was some change (difference).

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

Laravel Eloquent querying pivot table not unique

For some reason I don't get the expected result when doing the following:
$cars = Car::query();
$cars->whereIsVisible(true);
# output: $list
// [2016-01-16 09:30:04] local.INFO: array (
// 0 => 5,
// 1 => 7,
// 2 => 9,
// 3 => 3,
// )
$cars->whereHas('specifications', function($query) use ($list) {
$query->whereIn('id', ($list));
});
$cars->get();
What I expect is that I get only cars that have all the specifications that are inside that $list, but that's not correct. Even when I fill in more specifications, I get a bigger result. So there goes something wrong.
I'm used to Eloquent, so I suck in queries. But this is the Query:
select * from "cars" where "cars"."deleted_at" is null
and "is_visible" = true
and (select count(*)
from "specs" inner join "car_specs"
on "specs"."id" = "car_specs"."facility_id"
where "car_specs"."car_id" = "cars"."id"
and "id" in (5, 7, 9 ,3)) >= 1
Anyone see where it goes wrong? And how to fix it?
According to https://laravel.com/docs/5.1/eloquent-relationships#querying-relations
whereHas just checks that you have cars with the provided specifications, not that it returns those cars that match your specifications.
I think you should use where directly.

ActiveRecord query

I have two models Project and UrlList. A project :has_many url_list and a url_list :belongs_to project.
Now I have array for project id's all_projects = [1,2,5,8,16]. I want to retrieve all the records from url_list where project_id is one of those from all_projects array. How do I write code for it?
You can pass an array as value for an attribute to where method:
all_projects = [1, 2, 5, 8, 16]
url_lists = UrlList.where(:project_id => all_projects)
It'll generate SQL query like that:
SELECT `url_lists`.* FROM `url_lists` WHERE `project_id`.`user_id` IN (1, 2, 5, 8, 16)

Resources