2017-11-25 3 views
0

誰もが一日の種類!私の問題の本質はこれです: 2つのモデルがありますContact and PhoneNum!モデルでの関係:編集接点の形でLaravel sync hasMany belongsTo配列を持つ

use Illuminate\Database\Eloquent\Model; 

class Contact extends Model 
{ 
    protected $table = 'contacts'; 
    public function phoneNums() 
    { 
     return $this->hasMany('App\Models\PhoneNum'); 
    } 
} 

PHONENUMモデル

class PhoneNum extends Model 
{ 
    protected $table = 'phoneNums'; 
    protected $fillable = ['phone_num']; 

    public function contact() 
    { 
     return $this->belongsTo('App\Models\Contact'); 
    } 
} 

、私はその名前と、この連絡先の電話番号を持つ配列を取得します。

ContactController

public function update(Request $request, $id) 
{ 
    $contact = Contact::find($id); 
    $contact->name = $request->name; 
    $contact->save(); 

    //what should I do with the array $request->phoneNums ???? 

    return redirect('/'); 
} 

私は、IDに接触して、これらの新しい電話番号を同期することはできません。これで私を助けることができますか?

答えて

0

まずは、$request->nameから$request->input('name')に変更してください。この変更により、この変数がフォームから来ていることを約5ヶ月後に知ることができます。

第2に、問題の解決策。これは一例です。適切な名前に変更し、変数をモデルの質量割り当てフィールドに追加する必要があります。

foreach($request->input('phoneNums') as $phoneNumber){ 
    $contact->phoneNums()->create([ 
     'number' => $phoneNumber 
    ]); 
} 

そして、あなたはあなたのコードをより読みフレンドリーを作ることができるので、PSRのルールを見てみましょう:http://www.php-fig.org/psr/

0

Public function update(Request $request, $id) 

{ 
    $contact = Contact::find($id); 
    $contact->name = $request->name; 
    $contact->save(); 
    $contact->phoneNums()->sync($request->phoneNums, true) 

    return redirect('/'); 
} 
以下のように機能を更新するためにsyncメソッドを追加します。
関連する問題