fetty
fetty

Reputation: 25

Laravel:Many to Many Relationship

Hello Am trying to create many to many relationship but I failed. I have two table requests_table and Users_table and the relationship is many to many I introduce associative table called request_user with attribute of user_id, request_id and user_reqId(primary key). what I want is to submit data(user_id and request_id) to the associative entity when user request for anything?. help please....

Upvotes: 0

Views: 68

Answers (2)

AddWeb Solution Pvt Ltd
AddWeb Solution Pvt Ltd

Reputation: 21681

You should try this:

request_tbl.php

public function users() {
        return $this->belongsToMany(User::class, 'request_user');
    }

user.php

public function requests()
{
    return $this->belongsToMany(RequestTbl::class, 'request_user');
}

Controller

    $request_tbl = new requests_table();
    $users = $request->users;
    $request_tbl->users()->sync($users);

Upvotes: 0

Prateek kumar
Prateek kumar

Reputation: 12

Many-to-many relations are slightly more complicated than hasOne and hasMany relationships. An example of such a relationship is a user with many roles, where the roles are also shared by other users. For example, many users may have the role of "Admin". To define this relationship, three database tables are needed: users, roles, and role_user. The role_user table is derived from the alphabetical order of the related model names, and contains the user_id and role_id columns.

Many-to-many relationships are defined by writing a method that returns the result of the belongsToMany method.

Happy coding:)-

Upvotes: 1

Related Questions