Reputation: 31
I have two models in Laravel that I want to relate to each other. A trip can have multiple users and a user can take multiple trips. The models are set up like this.
class Trip extends Model {
public function users() {
return $this->belongsToMany('App\User', 'trip_user', 'user_id', 'trip_id');
}
}
class User extends Model {
public function trips() {
return $this->belongsToMany('App\Trip', 'trip_user', 'trip_id', 'user_id');
}
}
The pivot table is called 'trip_user' and has ids for users and trips.
When I try to get a trips users via
$oTrip->users()
I get the belongs to many relationship
BelongsToMany {#267 ▼
#table: "trip_user"
#foreignPivotKey: "user_id"
#relatedPivotKey: "trip_id"
#parentKey: "id"
#relatedKey: "id"
#relationName: "users"
#pivotColumns: []
#pivotWheres: []
#pivotWhereIns: []
#pivotValues: []
+withTimestamps: false
#pivotCreatedAt: null
#pivotUpdatedAt: null
#using: null
#accessor: "pivot"
#query: Builder {#266 ▶}
#parent: Trip {#259 ▶}
#related: User {#264 ▶}
-currentlyAttached: null
}
When I do
$oTrip->users
I get an empty collection. I can confirm that there is indeed an entry in the table with the correct trip id and some user id.
What could be wrong?
Upvotes: 2
Views: 977
Reputation: 392
from the Laravel docs :
The third argument is the foreign key name of the model on which you are defining the relationship, while the fourth argument is the foreign key name of the model that you are joining to
I believe you have them switched. Try swapping trip_id with user_id in your Many-to-many relations
Upvotes: 1