MySql Query error in Laravel - laravel-5

I am using laravel 5.4. When trying to run
select * from `users` inner join `addprojects` on `users`.`emp_id` = `addprojects`.`emp_id` where `emp_id` = $emp_id)"
It produces:
"SQLSTATE[23000]: Integrity constraint violation: 1052 Column 'emp_id'
in where clause is ambiguous (SQL: select * from users inner join
addprojects on users.emp_id = addprojects.emp_id where
emp_id = $emp_id)"
$emp_id= Auth::user()->emp_id;
$projects_for_emp = DB::table('users')->join('addprojects', 'users.emp_id', '=', 'addprojects.emp_id')->where('emp_id', '$emp_id')->get();

emp_id in both tables , so can use users.emp_id or addprojects.emp_id
->where('users.emp_id', '=', $emp_id)

You have specified column name which exists in both tables, so use users.emp_id or addprojects.emp_id doesn't matter which one
Example:
$emp_id= Auth::user()->emp_id;
$projects_for_emp = DB::table('users')
->join('addprojects', 'users.emp_id', '=', 'addprojects.emp_id')
->where('users.emp_id', '$emp_id')
->get();

Because both users and addprojects tables have same named field "emp_id".
You can change your code like following.
$emp_id= Auth::user()->emp_id;
$projects_for_emp = DB::table('users')
->join('addprojects', 'users.emp_id', '=', 'addprojects.emp_id')
->where('users.emp_id', $emp_id)
->get();

Related

how to join query different table in laravel

I try to join three tables which are named attendances, categories, and users.
my code is
$Attendance= DB::table('users')
->join('categories','users.U_category_id', '=', 'categories.id')
->select('users.*','categories.batch_name')->get();
but I also need to join attendances table where attendances column User_A_ID and users table id are the same. How can I do this?
You can try it with
$Attendance= DB::table('users')
->join('categories','users.U_category_id', '=', 'categories.id')
->join('attendances','users.id', '=', 'attendances.User_A_ID')
->select('users.*','categories.batch_name')->get();

how to join 3 tables using laravel eloquent?

my table
Code:
function viewPDF()
{
$reports = Report::join('president_report', 'reports.id', '=', 'president_report.report_id')
->join('president_report', 'presidents.id', '=', 'president_report.president_id')->
select('reports.*')->where('president_report.report_id')
->filter()->latest()->get();
$pdf = PDF::loadView('reports.test1', ['reports' => $reports]);
return $pdf->stream('reports.pdf');
}
Error:
SQLSTATE[42000]: Syntax error or access violation: 1066 Not unique
table/alias: 'president_report' (SQL: select * from reports inner
join president_report on reports.id =
president_report.report_id inner join president_report on
presidents.id = president_report.president_id where
president_report.report_id is null order by created_at desc)
Use separate aliases for the two joins with the president_reports table:
function viewPDF() {
$reports = Report::join('president_report pr1', 'reports.id', '=', 'pr1.report_id')
->join('president_report pr2', 'presidents.id', '=', 'pr2.president_id')->
select('reports.*')->where('pr1.report_id')
->filter()->latest()->get();
$pdf = PDF::loadView('reports.test1', ['reports' => $reports]);
return $pdf->stream('reports.pdf');
}
Note that the second join looks suspicious to me, because I don't see where the presidents table is getting included in the join query. But the general solution to use problem is to alias president_report differently for the two joins.

How to do LEFT OUTER JOIN in Laravel raw expression

This raw query is working well with two commented lines.
$q = DB::table('stock_items')
->selectRaw('stock_parts.title')
->selectRaw('COUNT(*) as qtyAvailable')
->selectRaw('SUM(shipments.item_cost) as totalValue')
//->selectRaw('stock_alerts.minimum AS minimum')
->join('stock_parts', 'stock_items.stock_part_id', '=', 'stock_parts.id')
->join('shipments', 'shipments.id', '=', 'stock_items.shipment_id')
//->leftJoin('stock_alerts', 'stock_alerts.stock_part_id', '=', 'stock_items.stock_part_id')
->whereNull('stock_items.status')
->where('stock_items.current_stock_id', '=', $stockId)
->groupBy('stock_parts.id')
->get();
The commented lines are needed to get information from another table.
In raw SQL I was using LEFT OUTER JOIN and it works.
Uncommenting those lines it shows this error:
SQLSTATE[42000]: Syntax error or access violation: 1055
Expression #4 of SELECT list is not in GROUP BY clause
and contains nonaggregated column 'rdphone-dev.stock_alerts.minimum'
which is not functionally dependent on columns in GROUP BY clause;
this is incompatible with sql_mode=only_full_group_by (SQL: select stock_parts.title, COUNT(*) as qtyAvailable, SUM(shipments.item_cost) as totalValue, stock_alerts.minimum AS minimum from `stock_items` inner join `stock_parts` on `stock_items`.`stock_part_id` = `stock_parts`.`id` inner join `shipments` on `shipments`.`id` = `stock_items`.`shipment_id` left join `stock_alerts` on `stock_alerts`.`stock_part_id` = `stock_items`.`stock_part_id` where `stock_items`.`status` is null and `stock_items`.`current_stock_id` = 1 group by `stock_parts`.`id`)",
What is the correct way to do LEFT OUTER JOIN in Laravel 5.6?
Every field used in the select has to be included in the group by, I added the minimum column in the groupBy.
$q = DB::table('stock_items')
->selectRaw('stock_parts.title')
->selectRaw('COUNT(*) as qtyAvailable')
->selectRaw('SUM(shipments.item_cost) as totalValue')
->selectRaw('stock_alerts.minimum AS minimum')
->join('stock_parts', 'stock_items.stock_part_id', '=', 'stock_parts.id')
->join('shipments', 'shipments.id', '=', 'stock_items.shipment_id')
->leftJoin('stock_alerts', 'stock_alerts.stock_part_id', '=', 'stock_items.stock_part_id')
->whereNull('stock_items.status')
->where('stock_items.current_stock_id', '=', $stockId)
->groupBy('stock_parts.id', 'minimum')
->get();

Laravel: change a raw query in a "query-builder" or "eloquent" one

I have this Laravel Query Builder snippet that is working fine:
$records = DB::table('users')
->select(
DB::raw('users.*, activations.id AS activation,
(SELECT roles.name FROM roles
INNER JOIN role_users
ON roles.id = role_users.role_id
WHERE users.id = role_users.user_id LIMIT 1)
AS role')
)
->leftJoin('activations', 'users.id', '=', 'activations.user_id')
->where('users.id', '<>', 1)
->orderBy('last_name')
->orderBy('first_name')
->paginate(10);
Is there a way to avoid use of raw queries and get the same result? In other words, how can I write this in a more "query-builder" style? Can I also translate this into an Eloquent query?
Thanks
You can used selectSub method for your query.
(1) First create the role query
$role = DB::table('roles')
->select('roles.name')
->join('roles_users', 'roles.id', '=', 'role_users.role_id')
->whereRaw('users.id = role_users.user_id')
->take(1);
(2) Second added the $role sub query as role
DB::table('users')
->select('users.*', 'activations.id AS activation')
->selectSub($role, 'role') // Role Sub Query As role
->leftJoin('activations', 'users.id', '=', 'activations.user_id')
->where('users.id', '<>', 1)
->orderBy('last_name')
->orderBy('first_name')
->paginate(10);
Output SQL Syntax
"select `users`.*, `activations`.`id` as `activation`,
(select `roles`.`name` from `roles` inner join `roles_users` on `roles`.`id` = `role_users`.`role_id`
where users.id = role_users.user_id limit 1) as `role`
from `users`
left join `activations` on `users`.`id` = `activations`.`user_id`
where `users`.`id` <> ?
order by `last_name` asc, `first_name` asc
limit 10 offset 0"

How to use multiple 'where' clause with multiple tables with Eloquent ORM?

I have a database query with multiple 'JOIN' statements in my Laravel application, but I don't know how to correctly add a where clause to it.
Here is my function:
return Topic::join('blogs', 'topics.blog_id', '=', 'blogs.id')
->join('blog_subscriptions as us', function ($j) use ($userId){
$j->on('us.blog_id', '=', 'blogs.id')
->where('us.user_id', '=', $userId);
})
->take(Config::get('topic.topics_per_page'))
->offset($offset)
->get(['topics.*']);
I would like to add a 'where' clause to the 'topics' table - so I add a line where('rating', '>', 1), after "Topic::", so the code is like this:
Topic::where('rating', '>', 1)
->join('blogs', 'topics.blog_id', '=', 'blogs.id')
->join('blog_subscriptions as us', function ($j) use ($userId){
$j->on('us.blog_id', '=', 'blogs.id')
->where('us.user_id', '=', $userId);
})
->take(Config::get('topic.topics_per_page'))
->offset($offset)
->get(['topics.*']);
but it only leads to an error:
SQLSTATE[23000]: Integrity constraint violation: 1052 Column 'rating' in where clause is ambiguous (SQL: select topics.* from topics inner join blogs on topics.blog_id = blogs.id inner join blog_subscriptions as us on us.blog_id = blogs.id and us.user_id = 1 where rating > 1 limit 2 offset 0)
As the error message says, the column rating is ambiguous. Meaning SQL can't tell which column you mean because there might be another one in your join that's named rating as well.
In this situation it helps to clarify in which table the field is. This is simply done by using the [table].[field] syntax
where('topics.rating', '>', 1)

Resources