删除相关行 Laravel ['where clause' 中的未知列 'users.pasien_id']

Delete Related Row Laravel [Unknown column 'users.pasien_id' in 'where clause']

我试图删除相应的行。

Pasien table 大坝用户 table

当我在 pasien table 中删除一行时,与用户 table 相关的行也应该被删除。然而,这显示了一个让我感到困惑的错误,我是否在模型上错误地实现了 belongsTo 和 hasMany。

我试过反推(belongsTo和hasMany),还是报错。此问题的正确代码行是什么?

用户Table

巴仙Table

帕西恩模型

public function users()
    {
        return $this->hasMany('App\Users');
    }
public static function boot()
  {
    parent::boot();
      static::deleting(function($pasien) {
        $pasien->users()->delete();
      });
  }

用户模型

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

Pasien控制器

public function destroy(Pasien $pasien)
    {
        $pasien->delete();

        return redirect()->route('pasien.index')
        ->with('success','Pasien deleted successfully');
    }

问题是 Pasiens table 中的外键 iduser 不遵循 laravel 遵循的约定(它期望列名是 user_id 因为它指向 Users table)

如文档中所述Eloquent: Relationships

By convention, Eloquent will take the "snake case" name of the owning model and suffix it with _id.

要解决这个问题你必须提供你的自定义外键名称给belongsTohasMany,所以laravel可以确定两个table之间的关系正确。

用户模型中

public function pasien()
{
    return $this->belongsTo('App\Pasien', 'iduser');
}

并且在 Pasien 模型中

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