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
Related
Here's my code.
The database name is socapa.
class Student extends Model
{
...
public static function rsStuds(
$varSession_rsStuds,
$varCampus_rsStuds,
$varProgram_rsStuds,
$varSeason_rsStuds,
$startRow_rsStuds,
$maxRows_rsStuds) {
return Student::select(
'contacts.FirstName',
'contacts.LastName',
'contacts.ContactID',
'students.StudentID',
'registrations.CourseID',
'registrations.RegDate',
'contacts.City',
'contacts.State',
'contacts.Country',
'campuses.CampusName',
'programs.ProgramName',
'courses.SessionID',
'courses.CourseName',
'courses.Season',
'students.StudentID',
'programs.ProgramID',
'sessions.SessionID',
'sessions.SessionName',
'programs.ProgramName')
->join('registrations', 'students.StudentID', '=', 'registrations.StudentID')
->join('contacts', 'contacts.ContactID', '=', 'students.StudentContactID')
->join('courses', 'courses.CourseID','=', 'registrations.CourseID')
->join('campuses', 'campuses.CampusID', '=', 'courses.CampusID')
->join('programs', 'programs.ProgramID', '=', 'courses.ProgramID')
->join('sessions', 'sessions.SessionID', '=', 'courses.SessionID')
->where('courses.SessionID', 'LIKE', "%".$varSession_rsStuds."%")
->where('courses.CampusID', 'LIKE', "%".$varCampus_rsStuds."%")
->where('courses.ProgramID', 'LIKE', "%".$varProgram_rsStuds."%")
->where('courses.Season', '=', ''.$varSeason_rsStuds)
->groupBy('courses.ProgramID')
->orderBy('contacts.LastName')
->skip(''.$startRow_rsStuds)
->take(''.$maxRows_rsStuds)->get();
}
...
}
When I run the project, the error following bellow, appears.
Illuminate\Database\QueryException
SQLSTATE[42000]: Syntax error or access violation: 1055 'socapa.contacts.FirstName' isn't in GROUP BY (SQL: select contacts.FirstName, contacts.LastName, contacts.ContactID, students.StudentID, registrations.CourseID, registrations.RegDate, contacts.City, contacts.State, contacts.Country, campuses.CampusName, programs.ProgramName, courses.SessionID, courses.CourseName, courses.Season, students.StudentID, programs.ProgramID, sessions.SessionID, sessions.SessionName, programs.ProgramName from students inner join registrations on students.StudentID = registrations.StudentID inner join contacts on contacts.ContactID = students.StudentContactID inner join courses on courses.CourseID = registrations.CourseID inner join campuses on campuses.CampusID = courses.CampusID inner join programs on programs.ProgramID = courses.ProgramID inner join sessions on sessions.SessionID = courses.SessionID where courses.SessionID LIKE %1% and courses.CampusID LIKE %1% and courses.ProgramID LIKE %1% and courses.Season = -1 group by courses.ProgramID order by contacts.LastName asc limit 50 offset 0)
Go to the config folder and open database.php find mysql and change
'strict' => false,
I am developing an application in Laravel 5.6 I'm having a simple table with following columns:
company_id project_id company_role_id company_specialisation_id
And this represents the model AssociateCompanies, which has relation of company, project, role, specialisation now I am having some query to get the attribute:
$companies = AssociateCompany::whereHas('company', function ($q) use ($request) {
$q->whereHas('projectOwners', function ($q) use($request) {
$q->where('slug', $request->slug);
});
})->groupBy('company_id', 'company_specialisation_id')->with('company', 'role', 'specialisation');
I want to collect all unique fields with their counts from two columns company_id and specialisation_id, but groupBy is not giving me proper the results so I am unbale to proceed further:
SQLSTATE[42000]: Syntax error or access violation: 1055 Expression #1 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'conxn.project_associate_company.id' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by (SQL: select * from project_associate_company where exists (select , (select count() from project_associate_company where companies.id = project_associate_company.company_id and project_associate_company.deleted_at is null) as associated_projects_count from companies where project_associate_company.company_id = companies.id and exists (select * from projects inner join project_owner_relation on projects.id = project_owner_relation.project_id where companies.id = project_owner_relation.company_id and slug = lodha-patel-estate-tower-a-b-mumbai and projects.deleted_at is null) and companies.deleted_at is null) and project_associate_company.deleted_at is null group by company_id, company_specialisation_id)"
So I tried running raw queries like this:
$companies = AssociateCompany::whereHas('company', function ($q) use ($request) {
$q->whereHas('projectOwners', function ($q) use($request) {
$q->where('slug', $request->slug);
});
})->selectRaw(DB::raw('COUNT(*) AS count GROUP BY company_id , company_specialisation_id'))
->with('company', 'companyRole', 'specialisation')->get();
SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'GROUP BY company_id , company_specialisation_id from project_associate_company' at line 1 (SQL: select COUNT(*) AS count GROUP BY company_id , company_specialisation_id from project_associate_company where exists (select , (select count() from project_associate_company where companies.id = project_associate_company.company_id and project_associate_company.deleted_at is null) as associated_projects_count from companies where project_associate_company.company_id = companies.id and exists (select * from projects inner join project_owner_relation on projects.id = project_owner_relation.project_id where companies.id = project_owner_relation.company_id and slug = lodha-patel-estate-tower-a-b-mumbai and projects.deleted_at is null) and companies.deleted_at is null) and project_associate_company.deleted_at is null)"
Suggest me better way to get this. Thanks.
Initially I want to notice you can not "group by" inside the "select" statement.
So you can not aggregate the non-aggregated columns. This means is grouped fields can be has got multiple "role" so you can not "load" the "roles". The query should be like the one of the follows:
AssociateCompany::whereHas('company', function ($q) use ($request) {
$q->whereHas('projectOwners', function ($q) use($request) {
$q->where('slug', $request->slug);
});
})->select('company_id', 'company_specialisation_id', \DB::raw('COUNT(*) as cnt'))
->groupBy('company_id', 'company_specialisation_id')
->with('company', 'specialisation');
Or :
AssociateCompany::whereHas('company', function ($q) use ($request) {
$q->whereHas('projectOwners', function ($q) use($request) {
$q->where('slug', $request->slug);
});
})->select('company_id', 'company_specialisation_id', 'company_role_id', \DB::raw('COUNT(*) as cnt'))
->groupBy('company_id', 'company_specialisation_id', 'company_role_id')
->with('company', 'specialisation', 'role');
My suggestions are like this but I think you can solve it with raw MySQL queries rather than use to Eloquent.
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);
I have the following Eloquent Query in one of my Models:
return self::where('sequence', '=', $sequence)->where('interval', '=', $minutes)
->leftJoin('wallet', 'wallet_stats.wallet_id', '=', 'wallet.id')
->leftJoin('balance', function($join) use ($uid)
{
$join->on('balance.wallet_id', '=', 'wallet_stats.wallet_id')
->on('balance.user_id', '=', $uid);
})
->orderBy('volume', 'ASC')->get(['symbol', 'name', 'volume', 'start_price', 'end_price']);
The problem I'm having with this is the following error message:
Oops! SQLSTATE[42S22]: Column not found: 1054 Unknown column '2' in
'on clause' (SQL: select symbol, name, volume, start_price,
end_price from wallet_stats left join wallet on
wallet_stats.wallet_id = wallet.id left join balance on
balance.wallet_id = wallet_stats.wallet_id and
balance.user_id = 2 where sequence = 0 and interval = 1440
order by volume asc)
For some reason Eloquent insists on using the value of $uid (in the 2nd "on" join condition) as a column name rather than a literal value.
Does anybody know how to get around that and have it accept a literal value in such a join specification?
I can't quite seem to replicate your error however this is what I've used in past instances. Giedrius Kiršys' suggestion in the comment on your question is also good.
return self::where('sequence', '=', $sequence)->where('interval', '=', $minutes)
->leftJoin('wallet', 'wallet_stats.wallet_id', '=', 'wallet.id')
->leftJoin('balance', function($join) use ($uid)
{
$join->on('balance.wallet_id', '=', 'wallet_stats.wallet_id')
->on('balance.user_id', '=', \DB::raw($uid));
})
->orderBy('volume', 'ASC')->get(['symbol', 'name', 'volume', 'start_price', 'end_price']);
This assumes you haven't already imported DB, if you have get rid of the \
Use ->where() for 2nd on clause, such as
->leftJoin('balance', function($join) use ($uid)
{
$join->on('balance.wallet_id', '=', 'wallet_stats.wallet_id');
$join->where('balance.user_id','=', $uid);
})
Or, use the DB::raw() for on clause value
->leftJoin('balance', function($join) use ($uid)
{
$join->on('balance.wallet_id', '=', 'wallet_stats.wallet_id');
$join->on('balance.user_id', '=', DB::raw($uid));
})
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