我在向DB存储多个一对多关系值时遇到问题。
迁移:
Schema::create('articles', function(Blueprint $table)
{
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->string('title');
$table->string('slug', 100)->unique();
$table->LongText('body');
$table->text('excerp');
$table->integer('img_id')->unsigned()->nullable();
$table->integer('img_gal_id')->unsigned()->nullable();
$table->timestamp('published_at');
$table->timestamps();
$table->foreign('user_id')->references('id')->on('users');
$table->foreign('img_gal_id')->references('id')->on('image_galleries');
$table->foreign('img_id')->references('id')->on('images');
});
表格
{!! Form::label('title', 'Title:') !!}
{!! Form::text('title', null, ['class' => 'form-container']) !!}
{!! Form::label('images', 'Article Image') !!}
{!! Form::file('images[]', ['class' => 'form-container', 'multiple']) !!}
and so on....
Article.php的一部分
protected $fillable = ['title', 'user_id','slug', 'body', 'excerp','published_at', 'img_id', 'img_gal_id'];
/ **
* Articles from a user.
* One To Many Relasion
* @var array
*/
public function user()
{
return $this->BelongsTo('App\User');
}
/**
* Main Image for article.
* Many to One Relasion
* @var array
*/
public function Image()
{
return $this->BelongsTo('App\Image');
}
图像
/**
*One to many relasionship with article entity
*/
public function articles()
{
return $this->HasMany('App\Article');
}
控制器
public function store(CreateArticleRequest $request)
{
$images = Input::file('images');
$imgobj = new Image;
// Imgprof = Upload the file and store it to db
$imgobj-> Imgprof($images);
// Uploaded img id :
$Uploadedimgid = $imgobj->Getimgids();
$article = \Auth::user()->articles()->create($request->all());
}
我将2个obj存储到db(Image - imgobj和Article)
我设法将用户ID存储到数据库,但是现在如何将$ uploadedimgid的值存储到同一个$ article(到img_id)?
我尝试追加图片() - > $ imgobj,但没有成功。
谢谢!