简体   繁体   English

我如何通过1个请求填充2个数据透视表

[英]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 该表与2个注释器表具有“多对多”关系:组

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: 我从Post请求中获取数据,并将其放入Users表中,但是将“ group”字段写入控制器中的“ group_user”数据透视表中:

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 ? 但我还需要通过一个sql请求将数据从另一个Post字段“ categories”写入另一个数据透视表category_user,我该怎么做?

In order to link user to a set of groups/category using their IDs you need to use sync() method. 为了使用用户的ID将用户链接到一组组/类别,您需要使用sync()方法。 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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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