2016-04-30 62 views
1

假設我們有兩個模型:UsersPosts這些模型之間定義了多對多的關係 - 用戶可以有許多帖子,帖子可以有許多編輯者(用戶)。有沒有辦法將作業委託給Laravel中的另一項操作?

當這個表格被提交到PostsController,它的store行動不僅必須處理新的職位的領域,而且它的編輯,這似乎是錯誤的。例子:

enter image description here

public function store() 
{ 
    // creating a post 
    $post = Post::create(request()->get('post_fields')); 

    // adding editors to the post (this should be done somewhere else) 
    $editors = request()->get('editors'); 
    foreach($editors as $editor){ 
     $post->editors()->attach($editor->id); 
    } 

    return redirect('/'); 
} 

正如我已經提到的,這種做法似乎是錯誤的,笨拙的我。正因爲如此,我想代表編輯處理任務到PostsEditorsController,這將是一個單獨的控制器專用於posts-editors關係管理。所以store現在是這個樣子:

public function store() 
{ 
    // creating a post 
    $post = Post::create(request()->get('post_fields')); 

    $editors = request()->get('editors'); 
    PostsEditorsController::doSomething($post, $editors); // <-- just to show what I want to achieve 

    return redirect('/'); 
} 

我怎樣才能做到這一點?

回答

1

將此邏輯添加到Post模型的保存事件如何?

https://laravel.com/docs/5.2/eloquent#events

這樣,這個邏輯將調用的模型保存任何時間,節省你擔心保存,如果你在系統中添加編輯其他已同步的大驚小怪。

+0

這是解決此問題的好方法,但我認爲使用控制器來完成這項工作感覺更自然。另外,你會在其他沒有事件發生的框架中做什麼?糾正我,如果我錯了。 –

+0

你說得對,用事件處理控制器數據可能有點尷尬,但試圖進一步簡化這個可能會有些荒謬。您可以通過執行'$ post-> sync('editors',$ editors-> pluck('id'));',IIRC來輕鬆地將它們彙總成一行。這是一條線 - 不會變得更簡單。 – Josh

+0

這個問題更多關於**應該在哪裏完成,而不是**如何**。所以,'$ post-> sync('editors',$ editors-> pluck('id'));'必須留在'store'行爲中,還是應該到別的地方去?如果我們在'store'方法中有更多的「副作用」,它應該只存儲發佈數據,它會變得非常龐大。對不起,如果我不夠清楚。 –

相關問題