【问题标题】:Laravel hasManyThrough - save doesn't workLaravel hasManyThrough - 保存不起作用
【发布时间】:2018-03-26 09:58:59
【问题描述】:
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,
    ...
);

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

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

在我的控制器中:

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

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

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

【问题讨论】:

  • 这看起来更像belongsToMany (laravel.com/docs/5.5/eloquent-relationships#many-to-many) 而不是hasManyThrough。试试看 - 您可能必须指定文档中显示的列,并将使用 attach() 而不是 save()。此外,在您的 user_groups 数据透视表中,您可能不需要 id 列。
  • 你对,你能回答吗,我可以标记为已解决?

标签: php laravel eloquent has-many-through


【解决方案1】:

当然可以:

// 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);
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-22
    • 2014-05-12
    • 2018-06-26
    • 2018-09-15
    • 2018-09-25
    • 1970-01-01
    相关资源
    最近更新 更多