【问题标题】:Laravel replace collection value based on other collectionLaravel 根据其他集合替换集合值
【发布时间】:2021-07-25 02:10:54
【问题描述】:

两个集合:

$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 集合“userid”值以替换为真实姓名而不是数字?我想在不修改数据库的情况下将其发送给查看。

$orders 的预期结果:

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

【问题讨论】:

    标签: php laravel laravel-7 laravel-collection


    【解决方案1】:
    $orders = Orders::with('user')->get();
    

    在您的订单模型中:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-04-06
      • 2022-09-23
      • 1970-01-01
      • 2015-10-23
      • 2021-02-20
      • 2016-02-25
      • 2015-08-20
      • 1970-01-01
      相关资源
      最近更新 更多