Laravel 5.3: Eloquent hasMany update

544 Views Asked by At

I need to update the items for specific order with Eloquent. I have this models:

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');
    }
}

I have the api response like that:

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

    ]
];

So I make this

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

and I was trying to make this:

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

but that doesn't work. Is there any way to match the related model with API response and make update?

Thanks!

1

There are 1 best solutions below

3
On

You can use save():

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

Or update():

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