私はモデルがあります:ArtObjectsと写真:Laravel雄弁 - 1つのリレーションに多く
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('/');
}
問題:ユーザーが選択した添付したいのかをアートオブジェクトとの写真。写真はすでにdbに存在することに注意してください。私はオプションを試してみました - save()、associate()は何も助けませんでした。私の理解は、私が$ art_objectを使って()を保存できるはずの写真オブジェクトを見つけなければならないと、私が一度見つけた写真です。私はnew()を使い、DBから割り当ててPhotoオブジェクトに代入したいと思っています。しかし、私はこれが正しいことだとは思わない。私はこれが多対一関係を実装する最善の方法ではないと考えています。そして、この関係を保存する最良の方法は何ですか。ご助言をいただき、ありがとうございます!