I have Account model that has id, name, timestamps and other fields, I have AccountUser model with account_id and user_id fields, and I have User model with users ids.
I'm trying to get users by account (account has many users) using $this->hasManyThrough('App\User', 'App\AccountUser')->get(); but I have an error SQLSTATE[42S22]: Column not found: 1054 Unknown column 'users.account_user_id' in 'on clause' (SQL: select users.*, account_users.account_id from users inner join account_users on account_users.id = users.account_user_id where account_users.account_id = 1).
I don't need 'users.account_user_id' column, but it is in query, what to do? Thank you.
You have to define the relationships in the model not in the query .
For this case you should use hasOne attribute
You have to specify the relationship keys in the model :
// In the User class
public function account()
{
return $this->hasOne(UserAccount::class,'account_id','id');
}
An then call the relationship with
$user->account();
See documentation .
hasManyThrough (as all relationship) has a default value, if you don't put nothing in:
hasManyThrough('App\User', 'App\AccountUser')
It gets the default value create from name of Models.
From doc:
The first argument passed to the hasManyThrough method is the name of
the final model we wish to access, while the second argument is the
name of the intermediate model.
Typical Eloquent foreign key conventions will be used when performing
the relationship's queries. If you would like to customize the keys of
the relationship, you may pass them as the third and fourth arguments
to the hasManyThrough method.
third argument is the name of the foreign key on the intermediate
model. The fourth argument is the name of the foreign key on the final
model. The fifth argument is the local key, while the sixth argument
is the local key of the intermediate model:
See the doc:
https://laravel.com/docs/7.x/eloquent-relationships#has-many-through
Related
Before you mark this question as duplicate, please see the details :) I have a problem related to many to many relationship with custom columns linking
I have following tables
Employees
-Id
-brink_id <----- This is third party id I am saving of employee
-name
Jobs
-id
-brink_id <----- This is third party id I am saving of job
-description
employee_job
-id
-brink_id <----- This is third party id I am saving of relationship for third party
-brink_employee_id
-brink_job_id
In Employee Model I have created relationship
public function jobs()
{
return $this->belongsToMany('App\Models\Job','employee_job','brink_employee_id','brink_job_id');
}
And in Jobs Model
/**
* #return \Illuminate\Database\Eloquent\Relations\BelongsToMany
*/
public function employees()
{
return $this->belongsToMany('App\Models\Employee','employee_job','brink_job_id','brink_employee_id');
}
Actually I want to have many to many relationship with brink_id in employees table and brink_id in jobs table presented as brink_employee_id, brink_job_id in employee_job table not with ID (primary columns of respective table).
But when I try to insert in pivot table using following, it always inserts employee ID rather than brink_id
$employee = Employee::with('jobs')->where('brink_id',$employeeJob['brink_employee_id'])->first();
$employee->jobs()->attach($employeeJob['brink_job_id'], ['is_active' => 1]);
For example if brink_id in employee table is 123456 and ID is 1, the above code in employee_table will store 1 in employee_brink_id rather than 123456.
Please let me know what I am doing wrong.
If you don't specify a different parent key and related key, it will default to your current model's primary key and the related model's primary key respectively.
Specify the parent key name as the 5th argument and the related key name as the 6th argument:
return $this->belongsToMany('App\Models\Employee', 'employee_job', 'brink_job_id', 'brink_employee_id', 'brink_id', 'brink_id');
However, I'd personally use the ids from your system and not the ids from a 3rd party system in your relationships.
I have a many-to-many relationship between projects and surveys. I can successfully create a relationship between a survey and a project with
$userSurvey = $project->surveys()->save($survey);.
This will create a new record inside the question_survey pivot table (The pivot table contains the columns id, question_id and survey_id.)
$userSurvey will receive the newly created survey model. Is there any way to receive also the id of the new record in the question_survey pivot table?
When retrieving many to many relationships, Laravel will automatically attach the pivot to the resulting Model, so in your case, $userSurvey will automatically have an attribute called pivot that holds, well, of course, the pivot.
But by default, that pivot attribute only holds the foreign keys, so in your case, the question_id and survey_id. If you have any other extra attributes,(in your case id), simply use the withPivot method, as follows.
public function surveys()
{
return $this->belongsToMany('App\Question', 'question_survey')
->withPivot('id');
}
Now you can access the id from the pivot table:
$userSurvey->pivot->id;
Bonus, if you think that the pivot word just does not fit your wording style, just use the as method in your relationship to customize the variable name of the pivot attribute.
public function surveys()
{
return $this->belongsToMany('App\Question', 'question_survey')
->as('question_survey')
->withPivot('id');
}
Now you can access the id from the pivot table:
$userSurvey->question_survey->id;
I am attempting to use HasManyThrough (which I think might be incorrect) to return the value of a column from a table via an intermediate table. From the File model I am attempting to access the Game table. The relations are:
A game can have many mods.
Many mods can have many files.
My table schema:
File Table
id - primary key
mod_id - foreign key
Mod Table
id - primary key
game_id - foreign key
Game Table
id - primary key
And this is how I am attempting to link them, I think the issue is there is only one Game for all the files I am attempting to find however I am not sure what the singular equivalent of HasManyThrough is?
In files.php the method I am attempting to use to map the relation is the following:
public function game()
{
return $this->hasManyThrough(
'App\Game',
'App\Mod',
'id',
'id',
'mod_id',
'game_id'
);
}
And I am attempting to get it via the following call:
$data = App\Files::with('game')->get();
Funny enough if I dump & die right after calling the above method it returns the game objects, but as soon as I attempt to eager load the relation, it returns an empty collection.
Any help would be greatly appreciated.
I'm new to Laravel and having problems with ManyToMany relationships.
I have two tables:
members
groups
A member can belong to many groups, a group can have many members.
I've created the relationships in the models and the pivot table.
When I create a member, I have checkboxes for the groups.
In my store method I do this:
....
$member->save();
if(isset($request->groups)) {
$groups = implode(',', $request->groups);
$member->groups()->sync([$groups]);
}
dd($groups) gives: "2,7"
I get the error:
QueryException in Connection.php line 761: SQLSTATE[01000]: Warning: 1265 Data truncated for column 'group_id' at row 1 (SQL: insert into group_member (group_id, member_id) values (2,7, 5))
Where is this 5 coming from and why do I get this error?
Thank you
This error is because of the data type you entered.
Using
implode()
You turn the array into a string while sync() method wants an array as input. Let's try just:
$member->save();
if(isset($request->groups)) {
$member->groups()->sync($request->groups);
}
To avoid the inconsistency that might arise due to the comma separated string, I'd convert
$request->groups, which is a string, to a standard array before adding it to the sync function.
if(isset($request->groups)) {
$groupIds = array($request->input('groups'));
$member->groups()->sync($groupdIds);
}
Following gives the list of ID's of SectionDetail Model while I need List of ID's of Section Model:
SectionDetail::with('section')->where('class_id', '=', Input::get('grade_id'))->lists('id');
Problem is both Models SectionDetail and Section has columns "ID".
How can I point to the ID of SectionDetail and Section Model in my Query
You can't do that this way, since there are 2 separate queries fetching SectionDetail and Section.
In order to get Section ids you need to query that model filtered by the relation constraint:
$gradeId = Input::get('grade_id');
// assuming sectionDetails is relation name on the Section model
$sectionsIds = Section::whereHas('sectionDetails', function ($q) use ($gradeId) {
$q->where('class_id', '=', $gradeId); // use prefixed column name in case it's ambiguous
})->lists('id');