2016-12-26 159 views
0

我需要更新與雄辯的具體順序項目。 我有這個型號:Laravel 5.3:雄辯有很多更新

class Orders extends \Illuminate\Database\Eloquent\Model 
{ 

    public $timestamps = false; 

    protected $fillable = ['items_array']; 

    public function items() 
    { 
     return $this->hasMany(Items::class, 'order_id', 'order_id'); 
    } 

    public function setItemsArrayAttribute($data) 
    { 
     $this->items()->whereIn('article_id', array_map(function($item){ 
      return $item['article_id']; 
     }, $data['items']))->update($data); 
    } 

} 

class Items extends \Illuminate\Database\Eloquent\Model 
{ 
    protected $table = 'order_to_items'; 

    public $timestamps = false; 

    protected $fillable = ['internal_code']; 

    public function order() 
    { 
     return $this->belongsTo(Orders::class, 'order_id', 'order_id'); 
    } 
} 

我有這樣的API響應:

$response = [ 
    'message'=>'some', 
    'order_id'=>'111-222-333', 
    'items'=>[ 
     [ 
      'article_id' => 'R-320108', 
      'internal_code' => 333 
     ], 
     [ 
      'article_id' => 'R-320116', 
      'internal_code' => 444 
     ], 

    ] 
]; 

所以我做這個

$order = Orders::where('order_id', $response['order_id'])->with('items')->first(); 

,我試圖讓這樣的:

$order->update([ 
    'is_sent' => true, 
    'items_array' => $response['items'] 
]); 

bu這不起作用。有沒有辦法將相關模型與API響應進行匹配並進行更新?

謝謝!

+0

是否有任何特定的錯誤,並請提供您的數據庫架構? –

回答

0

您可以使用save()

$order->is_sent = true; 
$order->items_array = $response['items']; 
$order->save(); 

或者update()

$order = Orders::where('order_id', $response['order_id']) 
       ->update([ 
        'is_sent' => true, 
        'items_array' => $response['items'] 
       ]); 
+0

它不起作用,因爲$ response ['items']數組中有兩個項目。在這種情況下,可能有一個匹配函數部分 – Toletov

+0

@Toletov只是迭代項目並更新每個項目。 –

+0

http://stackoverflow.com/questions/43109293/updateing-one-to-many-relation-in-laravel-5-3 這裏是問題的鏈接,請你能幫助我嗎? –