Reputation: 10886
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!
Upvotes: 1
Views: 13669
Reputation: 111
Firstly, I would suggest you rename your Model from CompanyModel
to 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);
Upvotes: 2