我有型號:ArtObjects和照片:Laravel雄辯 - 多對一關係
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);
}
}
控制器:
ArtObject控制器:
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('/');
}
問題:用戶希望選擇的附加與藝術對象的照片。請注意,照片已經存在於數據庫中。我試過選項 - save(),associate(),但沒有任何幫助。我的理解是我找到()它應該給我的照片對象,我應該可以用$ art_object保存()。它希望我new()並從數據庫中分配並分配給Photo對象。但我認爲這不是正確的做法。我相信這不是實現多對多關係的最佳方式,那麼節省這種關係的最好方法是什麼。請指教,謝謝!