Selecting items with join and without foreign key - php

I have query which gets each user's record from blacklist table and relations to them from rules table.
It looks like that:
$result1 = DB::table('blacklist')
->join('rules', 'blacklist.rule_id', '=', 'rules.id')
->select('blacklist.*', 'rules.clicks', 'rules.minutes')
->groupBy('blacklist.address')
->where('blacklist.user_id', JWTAuth::user()->id)
->get();
However I set field blacklist.rule_id as CAN BE NULL. Above query doesn't get records which have blacklist.rule_id == null(only these with values).
I have second query for that purpose:
$result2 = DB::table('blacklist')
->select('blacklist.*')
->groupBy('blacklist.address')
->where('blacklist.user_id', JWTAuth::user()->id)
->where('blacklist.rule_id', null)
->get();
But how to do it in one query?

It is actually an leftJoin instead of join:
$result1 = DB::table('blacklist')
->leftJoin('rules', 'blacklist.rule_id', '=', 'rules.id')
->select('blacklist.*', 'rules.clicks', 'rules.minutes')
->groupBy('blacklist.address')
->where('blacklist.user_id', JWTAuth::user()->id)
->get();

try this
$result2 = DB::table('blacklist')
->select('blacklist.*')
->groupBy('blacklist.address')
->where(function ($result2) {
$result2->where('blacklist.user_id', JWTAuth::user()->id)
->orWhereNull('blacklist.user_id');
}
->get();

Related

select all columns which are not in another table laravel 5.5

I have two tables - the first one is called 'users' and the second one is called 'buy_courses'.
I am trying to select all users those user_name is not in buy_courses. I tried something like -
$users = DB::table('users')
->rightjoin('buy_courses', 'users.user_name', '=', 'buy_courses.user_name')
->get();
It returns all users, whose user_name is in 'buy_courses', when I am using '<>', then I'm getting all users. What should be the right query?
DB::table("users")->select('*')->whereNotIn('user_name',function($query) {
$query->select('user_name')->from('buy_courses');
})->get();
just join actually is inner join in Laravel so actually maybe also you can try:
DB::table('users')
->join('buy_courses', 'users.user_name', '=', 'buy_courses.user_name')
->get();
Try it using Eloquent:
$courseUserNames = BuyCourses::pluck('user_name')->all();
$users = User::whereNotIn('user_name', $courseUserNames)->select(...)->get();
Or if you prefer using DB query:
$courseUserNames = DB::table('buy_courses')->pluck('user_name')->all();
$users = DB::table('users')->whereNotIn('user_name', $courseUserNames)->select(...)->get();
just replace = with != , use function join
$users = DB::table('users')
->join(
'buy_courses',
function ($join)
{$join->on('users.user_name', '!=', 'buy_courses.user_name');}
)
->get();
You can use SQL's 'NOT IN'.
Example:
mysqli_query($con, "SELECT * FROM users WHERE user_name NOT IN (SELECT user_name FROM buy_courses)");

selecting all fields from secondary table in eloquent

Is there any reason why my query doesn't end?, I try to get all the values from the secondary table in a join in eloquent:
Product::leftJoin('brands', 'products.brand_id', '=', 'brands.id')
->leftJoin('product_categories', function($query) use ($parent){
$query->on('products.category_id', '=', 'product_categories.id')
->where('product_categories.parent_id', $parent);
})
->selectRaw('brands.*')
->groupBy('brands.id')
->get();
If I select products.* the query goes fine, but with brands.* it never ends, Does someone knows what is happening?
If i run the sql directly in phpmyadmin, it gives me the result.
What i need with this query is to get all brands with existing products that its category has parent_id = $parent
Well i don't know why eloquent has a problem with getting the fields from the second table, but I used query builder so this query work. I leave my "solution", maybe it is useful to someone:
$brands = Product::leftJoin('brands', 'products.brand_id', '=', 'brands.id')
->leftJoin('product_categories', function($query) use ($parent){
$query->on('products.category_id', '=', 'product_categories.id')
->where('product_categories.parent_id', $parent);
})
->selectRaw('brands.*')
->groupBy('brands.id');
$bindings = $brands->getBindings();
$sql = $brands->toSql();
$sql = vsprintf(str_replace('?', '%s', $sql), $bindings);
$brands = \DB::select($sql);

Laravel 5 - compare query from one table to another query

I have two tables: a relationship table and a users table.
Relationship table looks like: 'user_one_id', 'user_two_id', 'status', 'action_user_id'.
Users table looks like: 'id', 'username'.
I would like to query the relationship table first and return an array of all the rows where the 'status' column = 0.
Then I would like to query the users table and return an array of ids and usernames where 'user_one_id' matches 'id'.
My code so far:
public function viewRequests()
{
$currentUser = JWTAuth::parseToken()->authenticate();
$friendRequests = DB::table('relationships')
->where('user_two_id', '=', $currentUser->id)
->where('status', '=', '0')
->get();
$requestWithUsername = DB::table('users')
->where('id', '=', $friendRequests->user_one_id)
->get();
return $requestWithUsername;
}
It's not working and I'm not sure what method is easiest to reach my desired output. How can I change these queries?
EDIT:
After reviewing the response, this is the working code:
$friendRequests = DB::table('users')
->select('users.id','users.username')
->join('relationships', 'relationships.user_one_id','=','users.id')
->where('relationships.status','=',0)
->where('relationships.user_two_id', '=', $currentUser->id)
->get();
Your SQL seems to be this:
SELECT id, username
FROM users
JOIN relationships
ON relationships.user_one_id = id
WHERE relationships.status = 0
Then the Laravel way:
DB::table('users')
->select('id','username')
->join('relationships', 'relationships.user_one_id','=','id')
->where('relationships.status','=',0)
->get();

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

Count rows in Laravel 4 database

Hi I am trying to get the current count of my statement below , but I am getting only the count not the whole result:
$admins = DB::table('users')
->select(DB::raw('count(users.id) as admin_count'))
->where('users_roles.role_id', '=' ,0)
->join('users_roles', 'users.id', '=', 'users_roles.user_id')
->orderBy('first_name', 'asc')
->get();
Could you tell me what I am doing wrong?
Thanks
Just use * in your SELECT clause, and you get entire resultset. Then, $admins is an array, and you can get its count using count method.
$admins = DB::table('users')
->select('users.*')
->join('users_roles', 'users.id', '=', 'users_roles.user_id')
->where('users_roles.role_id', '=' ,0)
->get();
I assume you have users_roles.role_id = 0 for exactly once for a user. There are no multiple entries for role_id = 0 for one user right?
I hope this helps.
Or you can use...
$admins = User::roles()->where('role_id', '=', 0)->count();
If the relations are setup correctly that should work.
Resource: http://laravel.com/docs/eloquent#many-to-many
I am not sure how laravel handles nested selects with the query builder, in plain sql, it would look like this
SELECT users.id, (SELECT COUNT(users.id) FROM users) AS admin_count
FROM users
JOIN users_roles
ON user_roles.id = users.id
WHERE users_roles.role_id = 0
ORDER BY first_name
which I am pretty sure you can just assign to a variable and run it like $admins = DB::query($sql)

Categories