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);
}
Related
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
Why I have got 3 values when I attach "dresscodes"?
$event->dresscode()->attach($request->get('dressCodesValue'));
this is error message
SQLSTATE[01000]: Warning: 1265 Data truncated for column 'dress_codes_id' at row 1 (SQL: insert into `dress_codes_events` (`dress_codes_id`, `events_id`) values (1,2, 28))
Here is a relation of Events table
public function dresscode()
{
return $this->belongsToMany(DressCodes::class);
}
Here are dresscode value when print out from controller $request->get('dressCodesValue') // 1,2
I fixed it.
Here is my problem
When I pass my data into FormData() and post it via axios.post It's converts my array value into string
Solution
just explode string back to array and pass that value into attach() method
I have a Student model and a corresponding one to one mapping relationship to Result model.
I have an eligibleList array containing a list of student id whose marks are to be displayed. Some student have results while some does not have but i need to display all of them from the list.
I am able to retrieve and display students using the following:
$students = Student::with('result:student_id,marks')->whereIn('students.id', $eligibleList)->get();
foreach($students as student) {
if ($student->result != null)
Log::debug($student->result->marks)
else
Log::debug("-1") //-1 indicate no results
}
The above has no issue until i need to sort the list (ascending or descending) by the marks. I tried the following:
$students = Student::with(['result:student_id,marks' => function ($query) {
$query->orderBy('marks','DESC');
}])->whereIn('student.id', $eligibleList)->get();
It throws me a "Call to undefined relationship" error. Is there anyway to sort from the query ? I avoid sorting the collection as it can get very slow for thousands of records. Somehow eloquent early loading encounter some error when sorting with non existence relationship.
you should use 'Subquery Ordering', ordering inside 'with' will not sort the overall result.
$students = Student::with(['result:student_id,marks'])->whereIn('student.id', $eligibleList)
->orderByDesc(Result::select('marks')->whereColumn('student_id','students.id'))
->get();
https://laravel.com/docs/7.x/eloquent#advanced-subqueries
if you use laravel 5 you have to use 'join':
Student::with(['result:student_id,marks'])->whereIn('student.id', $eligibleList)
->join('result','result.student_id','student.id')
->select('user.*,result.marks')->orderBy('result.marks')->get();
'join' use table name not the relation name, so please be careful about table name in previous 'join' and 'select' statements
In the following code, The Users table has a related table phoneNumbers. When I retrieve a list of all users like this,
return Person::with('phoneNumbers')->get();
everything works fine. However, when I attempt to specify a list of columns to return from the Person table, the phone_number returns empty.
return Person::with('phoneNumbers')
->get(['fname','lname', 'email']);
If I add the number field or phone_number.number to the get array, then I get an error as an undefined column. What is the laravel way of handling this.
Try this:
return Person::select(['your_foreign_key', 'fname','lname', 'email'])
->with('phoneNumbers')get();
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.