简体   繁体   中英

how i can fill 2 pivot table by 1 request laravel

I have table Users

class User extends Authenticatable
{
    use Notifiable;

    protected $guarded = ['group_c', 'group_s', 'categories'];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];

    public function groups()
    {
        return $this->belongsToMany('App\Group');
    }

    public function categories()
    {
        return $this->belongsToMany('App\Category');
    }
}

this table have relation 'many to many' to 2 anoter tables: Group

class Group extends Model
{
    public function users()
    {
        return $this->belongsToMany('App\User');
    }
}

and Category

class Category extends Model
{
    public function Users()
    {
        return $this->belongsToMany('App\User');
    }
}

I take data from Post request, and put them to Users table ,but 'group' field I write into 'group_user' pivot table, in my controller:

class UserController extends Controller
{

    public function create_user(CrateNewUser $request)
    {
        //dd(Request::all());
        if (Request::input('user_type') == '1') {
            $groups = Request::input('group_c');
            $categories = Request::input('categories');
            User::create(Request::all())->groups()->attach($groups);
        } elseif (Request::input('user_type') == '2') {
            $groups = Request::input('group_s');
            $categories = Request::input('categories');
            User::create(Request::all())->groups()->attach($groups);
        }

        return $this->manage_users();
    }
}

but I need also write data from another Post field 'categories' to another Pivot table categories_user by one sql request, how i can do that ?

In order to link user to a set of groups/category using their IDs you need to use sync() method. It will update the pivot table so that only synced records are linked.

The following should do the trick:

$user = User::create(Request::all());
$user->groups()->sync($groups);
$user->categories()->sync($categories);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM