2017-05-03 60 views
0

我有型號: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對象。但我認爲這不是正確的做法。我相信這不是實現多對多關係的最佳方式,那麼節省這種關係的最好方法是什麼。請指教,謝謝!

回答

1

根據數據庫中的多對一關係規則,連接表的外鍵始終保存在具有「多」關係的表中。

像這樣,一個ArtObject可以有很多Photos.So,那個「Many」表是Photos。您的照片模型必須具有名爲art_object_id的屬性作爲外鍵。

然後,您必須首先保存該ArtObject對象,並將該對象的ID保存在照片表中所有由用戶選擇其ID的行中。

$art_object = ArtObject::create(request(['title', 'description', 'rating', 'popularity', 'type', 'price'])); 

$this->validate($request, [ 
    'title' => 'required', 
    'description' => 'required' 
]); 

//save the artobject to the database 
$art_object->save(); 

foreach ($photo_ids = Input::get('photos') as $photo_id) { 

    $photo = Photo::find($photo_id); 
    $photo->art_object_id = $art_object->id; 
    $photo->save(); 


} 

這樣做後,你可以通過你在照片模式定義爲涉及ArtObject和照片表together.You也可以獲取由定義相關的ArtObject照片的方法取照片的相關ArtObject ArtObject中的方法。

在ArtObject型號: -

public function photos() 
{ 
    return $this->hasMany('App\Photo'); 
} 

在照片模式: -

public function artObject() 
{ 
    return $this->belongsTo('App\ArtObject'); 
}