我正在致力於laravel-4
應用程序。目前它很好地融合在一起,我一直在定義數據庫各個表之間的關係。不過,我遇到了一個問題,我遇到了麻煩。多對多關係Laravel 4
在我的數據庫中有一個資源表和標籤表。他們之間有多對多的關係,所以我也有一個resource_tags表,其中有兩個表id
作爲foreign keys
。
現在,當我基於用戶通過表單提供的數據創建資源時,我將創建資源,檢查類型並決定一個操作。然後,我檢索資源的標籤並通過它們進行循環,並創建表格的Tags
表項。
我的問題是將信息放入resource_tags表中。有沒有一種方法可以使我相對容易地做到這一點?
這是我controller
正在處理表單提交:
class SharedResourcesController extends BaseController {
//Add a shared Resource to the DB
//To do: Error checking and validation.
public function handleResource(){
//Create Object
$resource = new SharedResource;
$resource->title = Input::get('title'); //Title of resource
$resource->user_id = Input::get('user_id'); //User who uploads
$resource->book_id = Input::get('book_id'); //Book it is associated with
$resource->type_id = Input::get('type_id'); //Type of resource
//STORE LINKS
//if type is link... 1
if($resource->type_id == "1"){
$resource->web_link = Input::get('link');
}
//if type is video...2
if($resource->type_id == "2"){
$resource->vid_link = Input::get('link');
}
//UPLOADING
//If type is doc...3
if($resource->type_id == "3"){
if(Input::hasFile('file')){
$destinationPath = '';
$filename = '';
$file = Input::file('file');
$basename = Str::random(12);
$extension = $file->getClientOriginalExtension();
$destinationPath = public_path().'/file/';
$filename = Str::slug($basename, '_').".".$extension;//Create the filename
$file->move($destinationPath, $filename);
$resource->doc_link = $filename;
}
}
//if type is img...4
if($resource->type_id == "4"){
if(Input::hasFile('file')){
$destinationPath = '';
$filename = '';
$file = Input::file('file');
$basename = Str::random(12);
$extension = $file->getClientOriginalExtension();
$destinationPath = public_path().'/img/uploads/';
$filename = Str::slug($basename, '_').".".$extension;//Create the filename
$file->move($destinationPath, $filename);
$resource->img_link = $filename;
}
}
//TAGS
//Get the tags
$tags = Array();
$tags = explode(',', Input::get('tags'));
foreach($tags as $tag){
//Create a new Tag in DB - TO DO: Only Unique TAGS
$newTag = new Tag;
$newTag->name = $tag;
$newTag->save();
//Enter to resource tags
}
//Entry to resouce_tags
//Save Object
$resource->save();
return Redirect::action('[email protected]')->with('success', 'Resouce Created!');
//Any errors return to Form...
}
}
MODELS
class SharedResource extends Eloquent{
//set up many to many
public function tags(){
return $this->belongsToMany('Tag');
}
和
class Tag extends Eloquent{
//set up many to many
public function sharedResources(){
return $this->belongsToMany('SharedResource');
}
我知道有很多的驗證方面的缺失和錯誤處理,但我只是想獲得flo工作,我可以在以後修改它。我會很感激任何幫助。
只是澄清一下,你問你是否可以一次將多個標記保存到特定的資源,同時也將這些樞軸關係插入到resource_tag數據透視表中? – Patrick 2014-08-27 12:57:09
是的,這正是我需要做的 – Javacadabra 2014-08-27 12:57:48
順便說一下,據我所知,如果你希望Laravel能夠實現它,你的數據透視表應該使用單數:'resource_tag'而不是'resource_tags'。也就是說,你顯然已經在重寫表名,因爲你的'resources'表的模型被稱爲'SharedResource'。 – alexrussell 2014-08-27 14:45:18