2017-05-03 59 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'); 
}