简体   繁体   中英

Laravel 5 insert pivot table with attributes

I've been learning laravel for a few days now and I was hoping you guy's could help me. I have the following table structure:

users
------
id


companies
------
id


company_user
------
company_id
user_id
owner

My User and Company models have functions specified like this:

User Model

public function companies() {
    return $this->belongsToMany('App\Company', 'company_user', 'company_id', 'user_id')->withPivot('owner');
}

Company Model

public function users() {
    return $this->belongsToMany('App\User', 'company_user', 'company_id', 'user_id')->withPivot('owner');
}

For example when I save a company to a user like this:

User::find(1)->companies()->save(\App\Company::find(1));

The pivot table gets filled nicely, but the owner column doesn't get filled. I can't find many online how to fill this column. Hope you guys can help me?

Thanks in advance!

您可以将其他数据作为第二个参数传递给save()

User::find(1)->companies()->save(\App\Company::find(1), ['owner' => 'foo']);

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