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)
Related
I have following temp tables I wanna join them In query builder but I am failing to do so. I wanna join these 2 tables so I can do i1.imp/i2.imp
$subQuery1 = MyModel::query()
->from("table as i1")
->select(
\DB::raw('sum(col) as col1'),
\DB::raw('co1')
)->where('stamp', '>=', '2022-03-01 14:25:00')
->where('stamp', '<', '2022-03-07 14:30:00')
->groupBy(
'co1'
);
$subQuery2 = MyModel::query()
->from("table as i2")
->select(
\DB::raw('sum(col) as col1'),
\DB::raw('co1')
)->where('stamp', '>=', '2022-03-01 14:20:00')
->where('stamp', '<', '2022-03-07 14:25:00')
->groupBy(
'co1'
);
You can use from, fromSub or table and pass in a subquery instead of a table.
You can do the same with joinSub for joins.
You need to provide an alias though.
For example, to use $subquery1 as the main table and join it with $subquery2, the resulting query could look like this:
$results = DB::query()
->select(.....)
->fromSub($subquery1, 'i1')
->joinSub($subquery2, 'i2', function ($join) {
$join->on('i1.col', '=', 'i2.col');
// ->orOn(....)
});
->where(....)
->get();
Laravel 9.x API - fromSub
Queries - Subquery Joins
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();
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.
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();
I am using laravel 5.3 and I have some left join query with error in laravel query method.
This is my normal query
SELECT bran.branchName,sch.schoolName From m_schoolbranch bran
LEFT JOIN m_students stu ON stu.schoolNo=bran.schoolNo AND stu.branchNo=bran.branchNo
LEFT JOIN m_school sch ON sch.schoolNo=stu.schoolNo where stu.userNo='0000000001';
And this is my new laravel Query
DB::table('m_schoolbranch')
->join('m_students', 'm_schoolbranch.schoolNo', '=', 'm_students.schoolNo')
->join('m_students', 'm_schoolbranch.branchNo', '=', 'm_students.branchNo')
->join('m_school', 'm_schoolbranch.schoolNo', '=', 'm_school.schoolNo')
->select('m_school.schoolName', 'm_schoolbranch.branchName')
->where('m_students.userNo',$userNo)
->get();
In these query I need to match two column in table m_students so I put like this
->join('m_students', 'm_schoolbranch.branchNo', '=', 'm_students.branchNo')
But i show error...
Tables in the query need to have unique names, otherwise the DB has no way of knowing which m_schoolbranch should be used when evaluating m_schoolbranch.schoolNo.
You could use unique table aliases in your join statements but I recommend using multiple conditions on the join. Just like you use in your original SQL query. See here: https://stackoverflow.com/a/20732468/4437888
DB::table('m_schoolbranch')
->join('m_students', function($join)
{
$join->on('m_schoolbranch.schoolNo', '=', 'm_students.schoolNo');
$join->on('m_schoolbranch.branchNo', '=', 'm_students.branchNo');
})
->join('m_school', 'm_schoolbranch.schoolNo', '=', 'm_school.schoolNo')
->select('m_school.schoolName', 'm_schoolbranch.branchName')
->where('m_students.userNo',$userNo)
->get();