I have two tables: 'Articles' and 'Images'. In my Articles
I have:
`...
'body'
'image-1'
'image-2'
'image-3'
'image-4'
...`
I want to relate every article with one, two, three,... images stored in my database. And, of course, all the images can be used by more than one article.
My question is about which kind of relationship should I use between them. I don't know if it would be better to use a pivot table article_image
(belongsToMany), or if I'm doing well using other kind of relationship. In that case... It would be good in that way?:
ImageModel.php
public function article()
{
return $this->hasMany('Article', 'article_id');
}
ArticleModel.php
public function image()
{
return $this->hasMany('Image', 'image_id');
}
EDIT:
Then, if I use a pivot table... Should I use some extra columns in my pivot table? Like...
$table->increments('id');
$table->integer('article_id')->unsigned()->index();
$table->foreign('article_id')->references('id')->on('articles')->onDelete('cascade');
$table->integer('image-1')->unsigned()->index();
$table->foreign('image_id')->references('id')->on('images')->onDelete('cascade');
$table->integer('image-2')->unsigned()->index();
$table->foreign('image_id')->references('id')->on('images')->onDelete('cascade');
...
$table->timestamps();
I suppose I should remove onDelete('cascade')
to avoid to lose my articles when delete an image?
EDIT 2:
In my Controller, I save the image in this way:
if(Session::get('imagen_1')){
$imagen = new Imagen;
$imagen->url = Session::get('imagen_1');
$imagen->user_id = Sentry::getUser()->id;
$imagen->save();
Session::forget('imagen_1');
}
Then, I create my article
(I call it 'actividad')
$actividad = new actividad;
$actividad->titulo = Input::get('titulo');
$actividad->actividad = Input::get('actividad');
(...)
$actividad->slug = Str::slug(Input::get('titulo'));
$actividad->user_id = Sentry::getUser()->id;
$actividad->save();
And, finally, I try to save the relation between both:
$actividad->imagens()->sync($imagen);
But it doesn't work... I'm having the next error message:
Argument 1 passed to Illuminate\Database\Eloquent\Relations\BelongsToMany::formatSyncList() must be of the type array, object given, called in /Applications/XAMPP/xamppfiles/htdocs/webs/lara4/edu1/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Relations/BelongsToMany.php on line 578 and defined