Laravel 有很多错误。 'site_id' 没有默认值

Laravel hasMany error. 'site_id' doesn't have a default value

我在控制器中有以下方法

public function store(Request $request)
{
    $site = Site::create([
        "path" => $request->path,
        "site_link" => $request->link,
    ]);

    if ($request->features) {
        $features = explode(',', $request->features);

        foreach ($features as $feature) {
            $site->features()->save(SiteFeature::create(["feature" => $feature]));
        }
    }

    return response()->json($site, 201);
}

站点模型有这个方法

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

这是我的 $fillable 属性 的 SiteFeature

protected $fillable = ['feature', 'site_id'];

由于某种原因我得到下一个错误

local.ERROR: SQLSTATE[HY000]: General error: 1364 Field 'site_id' doesn't have a default value (SQL: insert into site_features (feature) values (fes)) {"exception":"[object] (Illuminate\Database\QueryException(code: HY000): SQLSTATE[HY000]: General error: 1364 Field 'site_id' doesn't have a default value (SQL: insert into site_features (feature) values (fes))

Model::create 方法实际上在您的数据库中创建了一条记录,但由于您没有指定必需的 site_id,它失败了,这就是您看到此错误的原因。

您似乎在尝试使用 Laravel 的关系为网站保存一个新的 SiteFeature,但您传递的是一个已经存在的对象(如果查询没有失败)关系的 save 方法。

您需要将尚未保存到数据库的 SiteFeaturenew 实例传递给 save 方法:

$this->features()->save(new SiteFeature(['feature' => $feature]));

或者您可以使用关系的 create 方法来避免必须完全传递一个实例,您只需要提供属性:

$this->features()->create(['feature' => $feature]);

试试这个

在您的模型中 features

public function features()
{
  return $this->hasMany('App\SiteFeature','site_id','id');
}

你是模特SiteFeature

public function siteFeatures()
{
  return $this->belongsTo('App\features', 'site_id', 'id');
}
$site = Site::create([
    "path" => $request->path,
    "site_link" => $request->link,
]);

最后插入的 ID 不是 return...试试

$site = new Site;
$site->path = $request->path;
$site->site_link = $request->link;
$site->save();

关于这部分:

if ($request->features) {
    $features = explode(',', $request->features);

    foreach ($features as $feature) {
        $site->features()->save(SiteFeature::create(["feature" => $feature]));
    }
}

如果上面的代码不起作用,你可以这样做...

if ($request->features) {
    $features = explode(',', $request->features);

    foreach ($features as $feature) {
        $sf = new SiteFeature;
        $sf->feature = $feature;
        $sf->site_id = $site->id;
        $sf->save();
    }
}