我有一种表单,可以将数据添加到两个不同的表(文章和交易)。一篇文章有很多交易。一笔交易有一篇文章。用户在创建和编辑表单上输入的多个交易具有不同的交易名称。我可以在本地/vagrant 开发环境中很好地更新数据库的“交易”部分,但是当我在实时站点上尝试时,出现“从空值创建默认对象”错误。
它说问题出在我的 Articles Controller
的 update
函数中。
我使用的是 Laravel 5。
文章表有:id(primary)
、title
、image
、description
、地址
。
Deals 表包含:id(primary)
、dealname
、article_id (index)
、dayID
。
我在开发环境和实际环境之间看到的唯一区别是“交易”表上的索引 (article_id) 在 PHPMyAdmin 中旁边没有 key 图标。但外键 r/ship 设置正确。
您可以在此处查看所有代码:https://github.com/lakemck/gethappy
文章 Controller - 更新
public function update(ArticleRequest $request, $id)
{
$article = Article::findOrFail($id);
if( $request->hasFile('image') ){
// photo saving stuff.
}
$article->update($request->all());
for($i = 0; $i < sizeof($request->input('dealname')); $i++) {
//Error is supposedly on the next line.
$article->deals->where('dayID',($i + 1))->first()->dealname = $request->input('dealname')[$i];
$article->deals->where('dayID',($i + 1))->first()->save();
}
return redirect('/');
}
表单
{!! Form::model($article, ['route' => ['articleUpdate_path', $article->id], 'files' => true, 'method' => 'PATCH']) !!}
{!! Form::label('title','TITLE') !!}
{!! Form::text('title', null, ['class' => 'form-control']) !!}
{!! $errors->first('title','<p class="error">:message</p>')!!}
{!! Form::label('image','PHOTO') !!}
{!! Form::file('image', null, ['class' => 'form-control']) !!}
{!! Form::label('description','DESCRIPTION') !!}
{!! Form::textarea('description', null, ['class' => 'form-control']) !!}
@foreach ($article->deals as $deal)
@if($deal->dayID == '1' )
{!! Form::label('dealname','Monday') !!}
{!! Form::text('dealname[]', $deal->dealname, null, ['class' => 'form-control', 'id' => '1']) !!}
@endif
@if($deal->dayID == '2' )
{!! Form::label('dealname','Tuesday') !!}
{!! Form::text('dealname[]', $deal->dealname, null, ['class' => 'form-control', 'id' => '2']) !!}
@endif
@if($deal->dayID == '3' )
{!! Form::label('dealname','Wednesday') !!}
{!! Form::text('dealname[]', $deal->dealname, null, ['class' => 'form-control', 'id' => '3']) !!}
@endif
@endforeach
{!! Form::label('address','ADDRESS') !!}
{!! Form::text('address', null, ['class' => 'form-control']) !!}
{!! Form::close() !!}
文章模型
class Article extends Model
{
public function deals()
{
return $this->hasMany('App\Deal');
}
protected $fillable = array('title', 'photo', 'description', 'address');
}
交易模式
class Deal extends Model
{
public function article()
{
return $this->belongsTo('App\Article')->withTimestamps();
}
protected $fillable = array('dealname', 'article_id', 'dayID');
}
最佳答案
最后我不得不将 ArticlesController 更新函数中的代码更改为:
for($i = 0; $i < sizeof($request->input('dealname')); $i++) {
$deal = $article->deals()->where('dayID', $i + 1)->first();
$deal->dealname = $request->input('dealname')[$i];
$deal->save();
}
return redirect('/');
}
注意 Deals() 上的括号。
关于php - 部署到服务器后更新数据库时出错。拉拉维尔 5,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35833903/