Laravel Where Clause not working for Null values - php

I have a customers table and Customer as Model. I am trying to get all the customers except customer category with id 1. The customer_category_id can be nullable.
I have following query.
Customer::where('customer_category_id', '!=', 1)->with('customerMeta')->get();
Above query doesn't give the customers with null customer category id. What would be the reason ?
I need all the customers with category null or category not equals to 1
Any kind of suggestions are appreciated.

This should work:
Customer::where(function ($query) {
$query->where('customer_category_id', '!=', 1)
->orWhereNull('customer_category_id')
})
->with('customerMeta')
->get();
Good luck!

Because null is also not equal to 1. You should probably add ->whereNotNull('customer_category_id') to your query:
Customer::where('customer_category_id', '!=', 1)
->whereNotNull('customer_category_id')
->with('customerMeta')
->get();

That query should work.
You could try and run it in artisan tinker. Before you run the query activate query logging:
DB::connection()->enableQueryLog();
Then run the query.
Afterwards, run:
DB::getQueryLog();
You'll now see the query that was created. Copy this query into a SQL Client and tweak it.
Hope this helps.

Change your query like this:
Customer::where('customer_category_id', '!=', '1')->with('customerMeta')->get();
Because the 1 also means true, so you have to use a string .

If you want to return the null category as well, you can use whereNull
Customer::where('customer_category_id', '!=', 1)
->whereNull('customer_category_id')
->with('customerMeta')
->get();
or you can use multiple where clauses like this:
$query->where([
['customer_category_id', '!=', '1'],
['customer_category_id', '=', null],
...
])

Related

Use query 2 in query 1 to get all data inside one query

I have 3 tables :
*hinteractions (id, name...)
*effects (id, name...)
*hinteractions_has_effects (hinteractons_id, effects_id)
I might have one to many effects in a hinteractions et one hinteraction might have one to many effects, that's why I have this join table.
I have this Eloquent query :
Query 1 :
$informations_plante = DB::table('herbs')
->select('herbs.name as hname', 'herbs.sciname', 'herbs.id as herbid','hinteractions.id as hinteractionid','hinteractions.note as hinteractionnote','hinteractions.force_id','targets.name as targetname', 'forces.name as force_name')
->leftJoin('hinteractions', 'herbs.id', '=', 'herb_id')
->leftJoin('forces', 'forces.id', '=', 'force_id')
->leftJoin('targets', 'targets.id', '=', 'hinteractions.target_id')->where('herbs.id', $id)
//I would like to use the query 2 here to select effects.name with hinteraction.id used in this query to get effects' name in this query (I might have one to many).
->get();
Query 2 :
$hinteractions_has_effects = DB::table('hinteraction_has_effects')
->select(DB::raw('effect_id, hinteraction_id','effects.name'))
->where('hinteraction_has_effects', '=', hinteraction.id (from the query 1))
->get();
With query 1, I retrieve some informations like hinteractions_id.
I would like to use those hinteractions_id and use them in the query 2.
The best way will be to merge both queries (1 and 2) to get only one Eloquent query.
Do you have any idea ?
Try below query and let me know if this is what you're looking for -
$informations_plante = DB::table('herbs')
->select('herbs.name as hname', 'herbs.sciname', 'herbs.id as herbid','hinteractions.id as hinteractionid','hinteractions.note as hinteractionnote','hinteractions.force_id','targets.name as targetname', 'forces.name as force_name', 'effects.id as effects_id', 'effects.name as effects_name')
->leftJoin('hinteractions', 'herbs.id', '=', 'herb_id')
->leftJoin('forces', 'forces.id', '=', 'force_id')
->leftJoin('targets', 'targets.id', '=', 'hinteractions.target_id')->where('herbs.id', $id)
//added below lines
->leftJoin('hinteraction_has_effects', 'hinteraction_has_effects.hinteractons_id', '=', 'hinteractions.id')
->leftJoin('effects', 'hinteraction_has_effects.effects_id', '=', 'effects.id')
->get();
HTH!

Laravel 5.4 Query Builder - Where condition with 2 table fields

So I'm trying to use a query on selecting products that are on Critical Level. So basically, if the product's quantity is lower than its reorder_point, it'll be considered as Critical.
Here's my query that I'm using:
$products = DB::table('inventory')
->where('quantity', '<=', 'reorder_point')
->orderBy('quantity', 'asc')
->get();
But it only shows once the quantity of that row is set to 0 or less. So I'm asumming that the value of re_orderpoint in the where condition is 0.
But everything works when I use this query in phpMyAdmin:
SELECT * from inventory where quantity <= reorder_point
Laravel gives you whereColumn for comparing columns of same table. You can do it like this:
$products = DB::table('inventory')
->whereColumn('quantity', '<=', 'reorder_point')
->orderBy('quantity', 'asc')
->get();
See docs here.
Hope you understand.

set specific record to first in row laravel query builder

I want to set all records order by FIELD_NAME but only 1 record with specific id need to be remain at first.
How can i achieve this using laravel query builder
My current query is like,
$orders =Order::orderBy('status', 'desc')
->where('status','<>',5)
->paginate(10);
And i want id=123 stay at first.
Use orderByRaw and simple sql condition:
$orders = Order::orderByRaw('IF(id = 123, 0,1)')->orderBy('status', 'desc')
->where('status', '<>', 5)
->paginate(10);

Laravel 5.1: handle joins with same column names

I'm trying to fetch following things from the database:
user name
user avatar_name
user avatar_filetype
complete conversation_messages
with the following query:
static public function getConversation($id)
{
$conversation = DB::table('conversation_messages')
->where('belongsTo', $id)
->join('users', 'conversation_messages.sender', '=', 'users.id')
->join('user_avatars', 'conversation_messages.sender', '=', 'user_avatars.id')
->select('users.name', 'conversation_messages.*', 'user_avatars.name', 'user_avatars.filetype')
->get();
return $conversation;
}
It works fine so far, but the avatar's column name is 'name' like the column name from the 'users' table.
So if I'm using this query the to get the output via $conversation->name, the avatar.name overwrites the users.name
Is there a way to rename the query output like the mysql "as" feature at laravel 5.1?
For example:
$conversation->avatarName
$conversation->userName
Meh okay.. i've found a simple solution here
->select('users.name as userName', 'conversation_messages.*', 'user_avatars.name as avatarName', 'user_avatars.filetype')
As you can mention I've added the requested "as-Feature" next to the table.columnName
Take a look at this example of trying to join three tables staffs, customers and bookings(pivot table).
$bookings = \DB::table('bookings')
->join('staffs', 'staffs.id' , '=', 'bookings.staff_id')
->join('customers', 'customers.id' , '=', 'bookings.customer_id')
->select('bookings.id', 'bookings.start_time', 'bookings.end_time', 'bookings.service', 'staffs.name as Staff-Name', 'customers.name as Customer-Name')
->orderBy('customers.name', 'desc')
->get();
return view('booking.index')
->with('bookings', $bookings);
I had the following problem, simplified example:
$result = Donation::join('user', 'user.id', '=', 'donation.user_id')->where('user.email', 'hello#papabello.com')->first();
$result is a collection of Donation models. BUT CAREFUL:
both tables, have a 'created_at' column. Now which created_at is displayed when doing $result->created_at ? i don't know. It seems that eloquent is doing an implicit select * when doing a join, returning models Donation but with additional attributes. created_at seems random. So what I really wanted, is a return of all Donation models of the user with email hello#papabello.com
solution is this:
$result = Donation::select('donation.*')->join('user', 'user.id', '=', 'donation.user_id')->where('user.email', 'hello#papabello.com')->first();
Yeah, simply rename the column on either table and it should work.
Also what you can do is, rename the user.name column to anything, also rename sender column of conversation_messages to id and perform a natural join.

Laravel Query Builder - sum() method issue

I'm new to laravel and I have some issues with the query builder.
The query I would like to build is this one:
SELECT SUM(transactions.amount)
FROM transactions
JOIN categories
ON transactions.category_id == categories.id
WHERE categories.kind == "1"
I tried building this but it isn't working and I can't figure out where I am wrong.
$purchases = DB::table('transactions')->sum('transactions.amount')
->join('categories', 'transactions.category_id', '=', 'categories.id')
->where('categories.kind', '=', 1)
->select('transactions.amount')
->get();
I would like to get all the transactions that have the attribute "kind" equal to 1 and save it in a variable.
Here's the db structure:
transactions(id, name, amount, category_id)
categories(id, name, kind)
You don't need to use select() or get() when using the aggregate method as sum:
$purchases = DB::table('transactions')
->join('categories', 'transactions.category_id', '=', 'categories.id')
->where('categories.kind', '=', 1)
->sum('transactions.amount');
Read more: http://laravel.com/docs/5.0/queries#aggregates
If one needs to select SUM of a column along with a normal selection of other columns, you can sum select that column using DB::raw method:
DB::table('table_name')
->select('column_str_1', 'column_str_2', DB::raw('SUM(column_int_1) AS sum_of_1'))
->get();
You can get some of any column in Laravel query builder/Eloquent as below.
$data=Model::where('user_id','=',$id)->sum('movement');
return $data;
You may add any condition to your record.
Thanks
MyModel::where('user_id', $_some_id)->sum('amount')

Categories