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

时间:2018-08-30 12:55:56

标签: php mysql laravel dingo-api

我在控制器中有以下方法

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的{​​{1}}属性

SiteFeature

由于某些原因,我会遇到下一个错误

  

local.ERROR:SQLSTATE [HY000]:常规错误:1364字段“ site_id”   没有默认值(SQL:插入protected $fillable = ['feature', 'site_id'];   ({site_features)个值(fes)){“ exception”:“ [object]   (Illuminate \ Database \ QueryException(代码:HY000):SQLSTATE [HY000]:   常规错误:1364字段“ site_id”没有默认值(SQL:   插入值{fes)featuresite_features

3 个答案:

答案 0 :(得分:0)

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

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

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

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

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

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

答案 1 :(得分:0)

尝试

在您的模型features

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

您为SiteFeature建模

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

答案 2 :(得分:0)

$site = Site::create([
    "path" => $request->path,
    "site_link" => $request->link,
]);

不返回最后一个插入ID ...请尝试

$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();
    }
}