I'm trying to use join() in laravel5.1 but I'm getting this error:
QueryException in Connection.php line 666: SQLSTATE[23000]: Integrity
constraint violation: 1052 Column 'id' in where clause is ambiguous
(SQL: select * from quizzes inner join question_numbers on
question_numbers.quiz_id = quizzes.id and
question_numbers.question_id = multiple_choice.id inner join
multiple_choice on multiple_choice.id =
question_numbers.question_id where id = 1)
I have three tables here and I want to join these three tables. What I want first is to get a quiz where id = to a specific id then join the table question_numbers where question_numbers.quiz_id is = to the quiz.id then join the table multiple_choice where multiple_choice.id is = question_numbers.question_id and where question_numbers.question_type = multiple_choice.
What I have:
$quiz = DB::table('quizzes')->where('id', $id)
->join('question_numbers', function($join){
$join->on('question_numbers.quiz_id', '=', 'quizzes.id')
->on('question_numbers.question_id', '=', 'multiple_choice.id');
})
->join('multiple_choice', 'multiple_choice.id', '=', 'question_numbers.question_id')
->get();
dd($quiz);
First, you need to set a table aliaslike this quizzes as t for your table that belongs the where condition's id (I assume you meant quizzes table id column here) and then if you refer it inside where like where('t.id', $id), it will not complain about the ambiguous integrity because other table also have id column that's why it is showing you the below Query exception,
Column 'id' in where clause is ambiguous
Try like this,
$quiz = DB::table('quizzes as t')->where('t.id', $id)
->join('question_numbers', function($join){
$join->on('question_numbers.quiz_id', '=', 't.id');
})
->join('multiple_choice', 'multiple_choice.id', '=', 'question_numbers.question_id')
->get();
dd($quiz);
Related
I have four tables as follows.
Services_cats
Session_pat
Invoice_item
Invoice
id
id
id
id
name
services_cat_id
service_id
code
patient_id
invoice_id
discount
I need to have relations among them with one Eloquent query in Laravel. Below is what I have reached so far; I used many-to-many relations in the invoice table.
public function invoice_item()
{
return $this->belongsToMany(Session_pat::class, 'invoice_items', "invoice_id",
"service_id", "id", "id");
}
And I used this code to access the four tables.
$status4 = Invoice::select('id')->with(['invoice_item' => function ($q){
$q->select('id', 'services_cat_id')
->with(['service_cat' => function ($q) {$q->select('id as myid', 'name');}])
;}])
->where('id', 122)->get();
but I get this error
SQLSTATE[23000]: Integrity constraint violation: 1052 Column 'id' in
field list is ambiguous (SQL: select id, services_cat_id,
invoice_items.invoice_id as pivot_invoice_id,
invoice_items.service_id as pivot_service_id from session_pats
inner join invoice_items on session_pats.id =
invoice_items.service_id where invoice_items.invoice_id in
(122) order by id desc)
You Should Specific The Table Name, WHen Using Same Column Name In Query.
Rule: tableName.column EX: invoiceTable.id
$status4 = Invoice::select('TableName.id')->with(['invoice_item' => function ($q){
$q->select('TableName.id', 'services_cat_id')
->with(['service_cat' => function ($q) {$q->select('TableName.id as myid', 'name');}])
;}])
->where('TableName.id', 122)->get();
I want to convert the following SQL to Laravel.
SELECT COUNT('uc.*') AS count_down, bs.brand_name
FROM `user_activities` AS uc
JOIN brands AS bs ON uc.brand_id = bs.id
GROUP BY uc.brand_id
ORDER BY count_down DESC
LIMIT 5
But when doing this:
$top_donwload_list = DB::table('user_activities')
->leftJoin('brands', 'brands.id', '=', 'user_activities.brand_id')
->selectRaw('brands.*, brands.brand_name, brands.id, count(user_activities.action_type) as user_activitiesCount')
->groupBy('user_activities.brand_id')
->get();
I get this error:
SQLSTATE[42000]: Syntax error or access violation: 1055 'colorworld.brands.id' isn't in GROUP BY (SQL: select brands.*, brands.brand_name, brands.id, count(user_activities.action_type) as user_activitiesCount from user_activities left join brands on brands.id = user_activities.brand_id group by user_activities.brand_id)
I tried to set 'strict' => true, in database.php but I get the same error in Laravel 5.7.
Update:- database table
If I understood your question correctly, you are trying to find the count of user activities grouped by a brand's name. Also you want the top 5 records ordered by the ones with the most user activities.
So, the following should work:
$top_donwload_list = DB::table('user_activities')
->selectRaw("brands.brand_name, COUNT('user_activities.*') as user_activitiesCount")
->join('brands', 'brands.id', '=', 'user_activities.brand_id')
->groupBy('brands.brand_name')
->orderBy('user_activitiesCount', 'desc')
->take(5)
->get();
You can use Laravel Eloquent. I Assume that the relationship between brand and user_activities is one to many and Here, the "Brand" is the model of the brand entity.
$count = Brand::leftJoin
('user_activities', function($join_brands){
$join_brands-> on
('brands.id', '=','user_activity.brand_id');
)->orderBy('user_activities.count_down','desc ')
->groupBy('user_activities.brand_id')->count();
This is my model function in laravel blade. In this i have two table "admins" and "candidates" using join query i join the two table. But While running my code I probably get this below mentioned
error.
if ( Input::has('recordcreator') and $request->input('recordcreator') != NULL){
$querys->join('admins','admins.adminid','=','candidates.createdby');
$querys->where('admins.firstname', 'LIKE', '%'. $request->input('recordcreator') .'%')->orWhere('admins.lastname', 'LIKE', '%'. $request->input('recordcreator') .'%')->where('admins.status','1');
}
SQLSTATE[23000]: Integrity constraint violation: 1052 Column
'firstname' in order clause is ambiguous (SQL: select * from
rsi_candidates inner join rsi_admins on rsi_admins.adminid =
rsi_candidates.createdby where rsi_admins.lastname LIKE %ic%
and rsi_admins.status = 1 or rsi_admins.firstname LIKE %ic%
group by rsi_candidates.candidateid order by firstname asc limit
20 offset 0)
As i see your laravel error you may add the table name in front of your firstname column in orderby clause
Or you may also try this solution
open your database.php file located in config directory
Config->database.php in your mysql database array add this.
'strict' => false,
I'm having an issue on Laravel 5.4 when I try to use only one join it works ok and returns correct data, but their add another join it doesn't work.
$data = Player::select(DB::raw('CONCAT(familyName,", ",firstName) AS fullName'))
->where('firstname', 'like', '%'.$search.'%')
->orWhere('familyName', 'like', '%'.$search.'%')
->orderBy('familyName', 'asc')
->join('teams', 'players.primaryClubId', '=', 'teams.clubId')
->join('person_competition_statistics', 'players.personId', '=', 'person_competition_statistics.personId')
->addSelect(['players.*', 'teams.teamName', 'teams.teamNickname', 'teams.teamCode'])
->get()
->unique() //remove duplicates
->groupBy(function($item, $key) { //group familyName that starts in same letter
return substr($item['familyName'], 0, 1);
})
->map(function ($subCollection) {
return $subCollection->chunk(4); // put your group size
});
return $data;
Returned Error:
QueryException in Connection.php line 647:
SQLSTATE[23000]: Integrity constraint violation: 1052 Column 'familyName' in field list is ambiguous (SQL: select CONCAT(familyName,", ",firstName) AS fullName, `players`.*, `teams`.`teamName`, `teams`.`teamNickname`, `teams`.`teamCode` from `players` inner join `teams` on `players`.`primaryClubId` = `teams`.`clubId` inner join `person_competition_statistics` on `players`.`personId` = `person_competition_statistics`.`personId` where `firstname` like %% or `familyName` like %% order by `familyName` asc)
If you are joining table then you should give table alias. like team as t , players as p and then column name like p.playername
I'm trying to fetch records with an array of exceptions, here's what I tried (refer below)
$users_nowishlist = DB::table('employee')
->join('users', 'users.employee_id', '=', 'employee.employee_id')
->where('has_wishlist', '=', "0")
->whereNotIn('employee_id', ['MMMFLB003', 'guest_01', 'guest_02', 'guest_03'])
->where('employment_status', '=', 'ACTIVE')
->get();
so in this line was my records filter, means only records that does not equal to any of those 'employee_id' from the exceptions array will be return (refer below)
->whereNotIn('employee_id', ['MMMFLB003', 'guest_01', 'guest_02', 'guest_03'])
but instead I got this error (refer below):
SQLSTATE[23000]: Integrity constraint violation: 1052 Column
'employee_id' in where clause is ambiguous (SQL: select * from
employee inner join users on users.employee_id =
employee.employee_id where has_wishlist = 0 and employee_id
not in (MMMFLB003, guest_01, guest_02, guest_03) and
employment_status = ACTIVE)
any ideas, help please?
This happens because when you are doing the join there are two columns with the same name.
That's why on your join you prefix the employee_id with users. and employee.
Now on your whereNotIn you also have to prefix it, so the query engine knows which table column you are trying to reference. So you only have to add the prefix in your whereNotIn clause:
->whereNotIn('employee.employee_id', ['MMMFLB003', 'guest_01', 'guest_02', 'guest_03'])
->whereNotIn('employee.employee_id', ['MMMFLB003', 'guest_01', 'guest_02'])
when using join , these errors are expected if you have two fields have the same name in the tables you join between, so always try to fetch them like this
table_name.field_name