Laravel 根据其他 collection 替换 collection 值

Laravel replace collection value based on other collection

两个collection:

$users = User::select('id','name')->get();

//outcome  [{"id":"1","name":"John"},{"id":"2","name":"Peter"}]

$orders = Orders::all();

//outcome  [{"id":"1","userid":"1"},{"id":"2","userid":"2"}]

如何修改$orders collection "userid" 值以用真实姓名代替数字?我想在不修改数据库的情况下发送它来查看。

$订单的预期结果:

//outcome  [{"id":"1","userid":"John"},{"id":"2","userid":"Peter"}]
$orders = Orders::with('user')->get();

在您的订单型号中:

public function user(){
return $this->belongsTo(User::class,'userid');
}