Laravel 10 ManyToMany关系

huangapple go评论56阅读模式
英文:

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

Laravel 10 ManyToMany关系

However when I list or dd the results i only get 1 company.

Laravel 10 ManyToMany关系

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');
}

huangapple
  • 本文由 发表于 2023年5月13日 21:04:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/76242880.html
  • eloquent
  • eloquent-relationship
  • laravel
  • laravel-10
  • many-to-many

如何在 :?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定