gpt4 book ai didi

php - Laravel hasManyThrough - 保存不起作用

转载 作者:搜寻专家 更新时间:2023-10-31 20:59:33 24 4
gpt4 key购买 nike

table groups
(
id int auto_increment primary key,
...
);

table users
(
id int auto_increment primary key,
...
);

table user_groups
(
id int auto_increment primary key,
user_id int not null,
group_id int not null,
...
);

在我的组模型中,我有一个 hasManyThrough 关系来通过 user_groups 链接表访问用户。

class Group
{
function users()
{
return $this->hasManyThrough('\App\Models\User', '\App\Models\UserGroup', 'group_id', 'id', 'id', 'user_id');
}
}

在我的 Controller 中:

$user = User::find(2);
$group->users[] = $user;
$group->save();

所以 $group->users 是一个集合,我可以添加我的用户,但它没有保存。

如何在hasManyThrough 关系上添加记录?

最佳答案

当然你可以这样做:

// Find an existing User record
$user = App\User::find(2);

// Creates a new group instance
$group = new App\group(['name' => 'shokry']);

// effectively sets $group->User_id to 2 then saves the instance to the DB
$user->groups()->save($group);

模型

class User extends Model
{
public function groups()
{
return $this->hasMany(App\Group::class);
}
}

class Group extends Model
{
public function user()
{
return $this->belongsTo(App\User::class);
}
}

关于php - Laravel hasManyThrough - 保存不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46743908/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com