我有型号: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对象。但我认为这不是正确的做法。我相信这不是实现多对多关系的最佳方式,那么节省这种关系的最好方法是什么。请指教,谢谢!