I have Models: ArtObjects and Photos:
class Photo extends Model { protected $fillable = ['caption','description','alternative_text'];
public function artObject()
{
return $this->belongsTo('App\ArtObject');
}
} class ArtObject extends Model {
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'title',
'description',
'rating',
'popularity',
'type',
'price'
];
public function photos()
{
return $this->hasMany(ArtObjectPhoto::class);
}
}
Controllers:
ArtObject Controller:
public function store(ArtObjectUploadRequest $request) {
$art_object = ArtObject::create(request(['title', 'description', 'rating', 'popularity', 'type', 'price']));
$this->validate($request, [
'title' => 'required',
'description' => 'required'
]);
foreach ($photo_ids = Input::get('photos') as $photo_id) {
$photo = Photo::find($photo_id);
/*
Problem is here - The user wants to attach the selected photos with the art-object, ........ Please advise, thanks in anticipation !!! */
}
//save the artobject to the database
$art_object->save();
//And redirect to the home page
return redirect('/');
}
Problem: The user wants to attach the selected photos with the art-object. Note that the photos already exists in the db. I have tried options - save(), associate () but nothing helped. My understanding is once I find () the photo it should give me Photo object which I should be able to save () with $art_object. It wants me to new() and assign from DB and assign to the Photo object. But I don't think this is the right way of doing this. I believe this is not the best way of implementing the many-to-relation , then what is the best way saving this relation. Please advise, thanks in anticipation !!!
via Chebli Mohamed
Aucun commentaire:
Enregistrer un commentaire