How to get the not applied jobs in the job table laravel - php

$joblist = JobDetail::join('candidates', 'job_details.id', '=', 'candidates.job_detail_id')
->where('candidates.user_id', Auth::id())
->where('candidates.job_detail_id', null)
->get();
SELECT job_details.*
FROM job_details
LEFT JOIN candidates
ON job_details.id = candidates.job_detail_id
WHERE candidates.job_detail_id IS NULL AND candidates.user_id = Auth::id()
This SQL query is not working.
I want to get the jobs that user didn't apply
jobs and users mapping table - candidate table
job details table

Consider fetching jobList from the candidate table :
$joblist = candidates::leftjoin('JobDetail','candidates.job_detail_id','job_details.id')
->where('candidates.user_id',Auth::id())
->whereNull('job_detail_id')
->select('job_details.*')->get();

------------job details model---------------
public function candidates(){
return $this->hasMany(candidate::class);
}
------------controller logic---------------
$userId = Auth::id();
$joblist = JobDetail:: whereDoesntHave('candidates', function ($query) use ($userId){
$query->where('user_id', $userId);
})->select('job_details.*')->get();

Related

How to write this sql,left join,sum query in Laravel? How to use sum with left join in Laravel?

I want to write this query in laravel,
My table structures are
There is a user id
$user_id = Auth::id();
CARTS->
ID|USER_ID|FOOD_ID|QUANTITY|STATUS
FOOD->
ID|NAME|PRICE
SELECT sum(food.price*carts.quantity) as total
from carts
left join food on carts.food_id=food.id
where user_id=$user_id and status='0'
You can also try this way:
$res = DB::table('carts')
->select(DB::Raw('SUM(food.price*carts.quantity) AS total'))
->leftJoin('food', 'carts.food_id', 'foods.id')
->where('carts.user_id', $user_id)
->where('carts.status', 0)
->first();
Using Query Builder:
$amount = \DB::table('carts')
->where('carts.user_id', $user)
->where('carts.status', '!=', 0)
->leftJoin('foods', 'carts.food_id', 'foods.id')
->sum(\DB::raw('carts.quantity * foods.price'));

List conversation between 2 users in the correct order

I want to create a chat system on which i could list all the chats between specific 2 persons
I have 2 tables users and chats
my chats table have 3 columns - user_id, friend_id and chat
my User.php model file is like this
public function chats() {
return $this->hasMany('App\Chat');
}
For eg:
I want to list all the chat between user 1 and 3 without changing the order of the conversation
I can simply do it by doing $chats = Auth::user()->chats->where('friend_id', '=', $id); but this will only give the authenticated (which is user 1 or 3) users chats. But I want the conversation between both of them.
So I have found an alternate way to do that by
$first = Chat::all()->where('user_id', '=', Auth::user()->id)->where('friend_id', '=', $id);
$second = Chat::all()->where('user_id', '=', $id)->where('friend_id', '=', Auth::user()->id);
$chats = $first->merge($second);
But this way has some problems. This will not get the chats in the correct order. I think it is impossible to order it correctly.
So my question is how can I list the conversation between two persons in the correct order easily?
If you want more details about my problem you can just ask.
You should be able to do it in one query with parameter grouping, rather than executing two separate queries and then merging them.
Chat::where(function ($query) use ($id) {
$query->where('user_id', '=', Auth::user()->id)
->where('friend_id', '=', $id);
})->orWhere(function ($query) use ($id) {
$query->where('user_id', '=', $id)
->where('friend_id', '=', Auth::user()->id);
})->get();
This might also return your results in the correct order, just because without any sort criteria specified, databases will often return rows in the order they were inserted. However, without adding something to your chat table to sort by, (either a timestamp or an autoincrement id), there's no way to guarantee it.
Try like this
$first = Chat::all()->where('user_id', '=', Auth::user()->id)
->where('friend_id', '=', $id)->get();
$second = Chat::all()->where('user_id', '=', $id)
->where('friend_id', '=', Auth::user()
->id)->get();
$chats = $first->merge($second)
->sortBy('created_at');//created_at is timing added change if other
First of all, you should not do all() before filtering. This is bad because fetches all the table data and then does the filtering in PHP.
You should consider doing this:
In your migration:
Schema::create("chat", function (Blueprint $table) {
//Other creation lines
$table->timestamps();
})
Then in your chat model:
public function scopeInvolvingUsers($query, $userId,$friendId) {
return $query->where([ ["user_id",$userId],["friend_id",$friendId] ])
->orWhere([ ["user_id",$friendId],["friend_id",$userId] ]);
}
Then you can do the following:
$chats = Chat::involvingUsers(\Auth::id(),$otherId)->latest()->get();
Note that latest or earliest requires the timestamps to be present on the table.
I will add timestamps in chat table which will ensure the order.
To add timestamp into chat table just add
$table->timestamps();
and the you can select the chat related to the user and sort it by created_at.
In laravel 5.3+ use
Chats::where(['user_id', '=', Auth::id()], ['friend_id', '=', $id])->orWhere(['user_id', '=', $id], ['friend_id', '=', Auth::id()])->sortBy('created_at');
Chat::whereIn('user_id', [$id, Auth->user()->id])
->whereIn('friend_id', [$id, Auth->user()->id])->get();

Converting a complicated query to Laravel's Eloquent

I was wondering how I would go about converting this query to Laravel?
SELECT * FROM users INNER JOIN srp_user_statistics ON users.id = srp_user_statistics.user_id ORDER BY srp_user_statistics.payslips_collected DESC LIMIT 2
"users" table is in a modal called Player and the srp_user_statistics table is in a modal called Roleplay which is a relationship of modal Player called "roleplay"
I tried this, but its returning DESC even when selecting ASC:
$players = Player::whereHas('roleplay', function ($query) use($orderType) {
$query->orderBy('payslips_collected', $orderType);
})->get();
using Larvel Query Builder:
$record = DB::table('users')
->innerJoin('srp_user_statistics', 'users.id', '=', 'srp_user_statistics.user_id')
->orderBy('payslips_collected', 'DESC')
->limit(2)
->get();

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

Very slow eloquent query

I have a query in one of my controller in my Laravel controllers that looks like this,
$project = new Project;
$me = ResourceServer::getOwnerId();
$my_projects = Project::ManagedByMe($me)
->OwnedByOrganisationIAmIn($me)
->IAmACollaborator($me)
->NoArchived()
->get(array(
'projects.id',
'projects.name',
'projects.description',
'projects.total_cost',
'projects.sales_person',
'projects.slug',
'projects.uri_hash',
'projects.client_id',
'projects.start_date',
'projects.finish_date',
'projects.organisation_id',
'projects.locked_by',
'projects.created_at',
'projects.status',
'projects.owner_id',
'projects.user_id',
'projects.archived_at'
));
$my_projects->load('projectmanager');
$my_projects->load('clients');
$my_projects->load('organisations')->load('organisations.users');
$my_projects->load('collaborators');
$my_projects->load('status');
$my_projects->load('notifications')->load('notifications.user');
$my_projects->load(array('projectview'=>function($query){
$query->where('users.id','=',ResourceServer::getOwnerId());
})); 
It returns 898 rows of data, and takes over a minute to execute. I am using scopes in the query, that look like this,
public function scopeManagedByMe($query, $user_id) {
$query->distinct();
$query->leftJoin('project_managers', 'projects.id', '=', 'project_managers.project_id');
$query->where('project_managers.user_id', '=', $user_id);
}
public function scopeOwnedByOrganisationIAmIn($query, $user_id) {
$query->leftJoin('organisations', 'projects.organisation_id', '=', 'organisations.id');
$query->leftJoin('organisation_user', 'organisations.id', '=', 'organisation_user.organisation_id');
$query->orWhere('organisation_user.user_id', '=', $user_id);
}
public function scopeIAmACollaborator($query, $user_id) {
$query->leftJoin('collaborators', 'projects.id', '=', 'collaborators.project_id');
$query->orWhere('collaborators.user_id', '=', $user_id);
}
public function scopeNoArchived($query) {
$query->orWhere('projects.archived_at', '=', '0000-00-00 00:00:00');
$query->whereNull('projects.deleted_at');
}
and the SQL that is actually run looks like this,
select distinct `projects`.`id`,
`projects`.`name`,
`projects`.`description`,
`projects`.`total_cost`,
`projects`.`sales_person`,
`projects`.`slug`, `projects`.`uri_hash`,
`projects`.`client_id`,
`projects`.`start_date`, `projects`.`finish_date`,
`projects`.`organisation_id`,
`projects`.`locked_by`, `projects`.`created_at`,
`projects`.`status`,
`projects`.`owner_id`,
`projects`.`user_id`,
`projects`.`archived_at`
from `projects`
left join `project_managers` on `projects`.`id` = `project_managers`.`project_id`
left join `organisations` on `projects`.`organisation_id` = `organisations`.`id`
left join `organisation_user` on `organisations`.`id` = `organisation_user`.`organisation_id`
left join `collaborators` on `projects`.`id` = `collaborators`.`project_id`
where `projects`.`deleted_at` is null
and `project_managers`.`user_id` = ? or `organisation_user`.`user_id` = ?
or `collaborators`.`user_id` = ? or `projects`.`archived_at` = ?
and `projects`.`deleted_at` is null
What I am trying to do, is select all the projects that I belong to, either by virtue that I am in an organisation that owns a project, I am project manager of the project or a collaborator of the project.
At first set indexes on join-condition fields:
`projects`.`id`
`projects`.`organisation_id`
`project_managers`.`project_id`
`organisations`.`id`
`organisation_user`.`organisation_id`
`collaborators`.`project_id`
if some of them are not setted.
Then update your query execution time in question subject.

Categories