Reputation: 1858
I am trying to join two columns with a table.
Here is my table structure for tasks table
| id | assigned_by | assigned_to |
| :--- | :---: | ---: |
| 1 | 1 | 2 |
| 2 | 1 | 3 |
Here is the table structure of users table.
| id | name | email |
| :--- | :---: | ---: |
| 1 |varun | [email protected] |
| 2 |mark | [email protected]|
I tried below code in Task Class
it didn't work
public function user()
{
return $this->belongsTo(User::class);
}
Upvotes: 0
Views: 38
Reputation: 13394
Eloquent will automatically determine the proper foreign key column on the User model. By convention, Eloquent will take the "snake case" name of the owning model and suffix it with _id. So, for your example, Eloquent will assume the foreign key on the User model is user_id
.
However, your foreign_key is assigned_by
and assigned_to
, so you need to specify the foreign_key:
public function assignedUser()
{
return $this->belongsTo(User::class, 'assigned_to');
}
public function assignedByUser()
{
return $this->belongsTo(User::class, 'assigned_by');
}
Upvotes: 2