通过关系创建/保存

时间:2019-02-18 19:25:00

标签: php laravel relationship

我有以下型号:

  • 用户
  • 设备

以下是关系:

User belongsTo a group

Group hasMany Users

Device belongsTo group

如何通过用户创建Device

$user = Auth::user();

$new_device = new Device;
$new_device->ip = $request->input('ip');
$new_device->port = $request->input('port');
$new_device->community_name = $request->input('community_name');

$user->group->save($new_device);

使用时出现错误:

$user->group->save($new_device);

Argument 1 passed to Illuminate\Database\Eloquent\Model::save() must be of the type array, object given, called in /home/snmpexperiments/laravel/app/Http/Controllers/SnmpController.php on line 74

使用时出现错误:

$user->group()->save($new_device);

Call to undefined method Illuminate\Database\Eloquent\Relations\BelongsTo::save()

我有点困惑。应该通过组保存设备还是应该通过用户保存设备?

  

用户模型

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

public function devices()
{
    return $this->hasManyThrough('App\Device', 'App\Group'); // So i can get devices like $user->devices
}
  

组模型

public function users()
{
    return $this->hasMany('App\User');
}

public function devices()
{
    return $this->hasMany('App\Device');
}

public function interfaces(){
    return $this->hasManyThrough('App\ModelInterface', 'App\Device'); // So I can get interfaces through Device $group->interfaces
}
  

设备型号

public function interfaces()
{
    return $this->hasMany('App\ModelInterface');
}

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

2 个答案:

答案 0 :(得分:2)

正确的语法是$post->comments()->save($comment);。注意注释后的括号,该括号访问关系方法而不是属性。因此,在这种情况下,您将使用

$user->group->devices()->save($new_device);

答案 1 :(得分:0)

要通过组保存设备,您需要指定设备。

$user->group->device()->save($new_device);

您执行的操作方式是尝试保存组模型。 model-> save()可以接受一系列选项,这就是您收到该错误的原因。