1
votes

I've got a strange problem.

I've a users table and a company table. A User belongsTo a company and a company hasMany users.

Both primary keys of the table are id.

In the laravel documentation I read the following:

Additionally, Eloquent assumes that the foreign key should have a value matching the id column of the parent.

I've got this in my CompanyModel:

protected $table = 'company';

public function users()
   {
      return $this->hasMany(UserModel::class);
   }

When I try this:

$users = CompanyModel::find(1)->users;
dd($users);

It's not working. When I add a foreign key in my relation it works!?:

protected $table = 'company';

public function users()
  {
     return $this->hasMany(UserModel::class, 'id');
  }

This is strange right? What on earth am I doing wrong.

--EDIT--

In my users table I've got a company_id column!

1
Documentation suggests that you have a company_id column in users table. The result you get by adding 'id' is probably wrong.geoandri
I've got a company_id column in my users table!Jamie
I think you should have a company_model_id column in users table or add "company_id" in your relation instead of "id" as the foreign key.geoandri
you have also the belongsTo method in User model right?orestiss
Is it working $users = CompanyModel::find(1)->with('users');IshaS

1 Answers

2
votes

Firstly, I would suggest you rename your Model from CompanyModelto Company and from UserModel to User.

Then ensure you have company_id in your users table. And in your users migration file connect the users table with the companies table as such:


    $table->integer('company_id')->unsigned();
    $table->foreign('company_id')->references('id')->on('companies')->onDelete('cascade');

Don't forget to refresh your database.

Then in your models, define the relationships as such:


    // User model
    // Laravel will automatically identify and use the `company_id` field in your reference
    public function company(){
       return $this->belongsTo(Company::class);
    }

    // Company model
    public function users(){
       return $this->hasMany(User::class);
    }

You can then fetch your records in your controller as such:


    $user = User::find(1);

    $user_company = $user->company; // This might not be necessary in your controller, you can do it in your view

    dd($users, $user_company);