英文:
Laravel 10 ManyToMany relationship
问题
好的,我明白。
英文:
So, in my App an User can have multiple companies for which he can have records.
I have stated the following methods
User.php
public function companies() {
return $this->belongsToMany(Company::class, 'companies_users', 'company_id', 'user_id');
}
Company.php
public function users() {
return $this->belongsToMany(User::class, 'companies_users', 'company_id', 'user_id');
}
In CompanyController i'm attaching the user id on create using the following
public function store(StoreCompanyRequest $request) {
$company = \App\Models\Company::create($request->all());
$company->users()->attach(Auth::user()->id);
return redirect()->route('companies.index')->with('success','Company has been created successfully.');
}
Pivot table companies_users is updated just fine
However when I list or dd the results i only get 1 company.
Anyone knows what am I doing wrong?
Thank you
答案1
得分: 1
The problem is that the companies
relation on the User
model is incorrect. You should swap the position of user_id
and company_id
and it should work.
public function companies()
{
return $this->belongsToMany(Company::class, 'companies_users', 'user_id', 'company_id');
}
As a generic rule, for belongsToMany
relationships, the third parameter would have the name of the model you are defining on. For example, if you are defining the relation of the User
model, the third parameter would be user_id
.
Tip
Since your models follow Laravel naming standards, you could also just skip the 3rd and 4th parameters, and Laravel will guess it on its own.
public function companies()
{
return $this->belongsToMany(Company::class, 'companies_users');
}
英文:
The problem is that the companies
relation on the User
model is incorrect. You should swap the position of user_id
and company_id
and it should work.
public function companies()
{
return $this->belongsToMany(Company::class, 'companies_users', 'user_id', 'company_id');
}
As a generic rule, for belongsToMany
relationships, the third parameter would have the name of the model you are defining on. For example, if you are defining the relation of the User
model, the third parameter would be user_id
Tip
Since your models follow Laravel naming standards, you could also just skip the 3rd and 4th parameters and Laravel will guess it on its own.
public function companies()
{
return $this->belongsToMany(Company::class, 'companies_users');
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论