【发布时间】:2017-05-10 23:02:07
【问题描述】:
我需要使用 Eloquent 更新特定订单的商品。 我有这个模型:
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']
]);
但这不起作用。有什么方法可以将相关模型与 API 响应匹配并进行更新?
谢谢!
【问题讨论】:
-
是否有任何具体错误,请提供您的数据库架构?
标签: php laravel eloquent relationship has-many