php 如何在laravel中动态循环foreach

gkn4icbw  于 2022-12-21  发布在  PHP
关注(0)|答案(2)|浏览(217)

我只是学习Laravel,我有这个逻辑是在我想显示的总项目的基础上,从用户数组,进一步解释这一点,这里是我的数据库
用户表

项目表

这是我当前的代码

public function display()
    {
       
            $users = User::where('type', 'Shop')->get();

            foreach($users as $user){
                $shop_id = $user['id'];
                $shop_name = $user['name'];
            }
            $total = Item::where('user_id', $shop_id)->sum('total');
            $shops =[
                ['Name' => $shop_name, 'total' => $total],
            ];

            return response()->json([
                "shops" =>$shops
            ], 200);

    }

下面是我的示例输出:

我只得到1个对象,而不是2,因为我有两个商店如何循环动态。
谢谢

avwztpqn

avwztpqn1#

$shops$total变量不在foreach循环中,这是因为它只返回一行。您必须使用$shops[]

public function display()
    {
       
            $users = User::where('type', 'Shop')->get();

            foreach($users as $user){
                $shop_id = $user['id'];
                $shop_name = $user['name'];
                $total = Item::where('user_id', $shop_id)->sum('total');
                $shops[] =['Name' => $shop_name, 'total' => $total];
            }
           
            return response()->json([
                "shops" =>$shops
            ], 200);

    }

但最好的干净的方法是使用laravel关系
在用户模型中:

public function items()
{
return $this->hasMany(Item::class) ;
}

和显示控制器:

public function display()
 {
   $shops = User::where('type', 'Shop')->get()
            ->mapWithKeys(function($user){
               return ['name'=>$user->name ,
                       'total'=> $user->items->sum('total')
             ]});

  return response()->json(["shops" =>$shops], 200);

 }
llew8vvj

llew8vvj2#

这样做

$shops[] = ['Name' => $shop_name, 'total' => $total];

把所有的商店都放到一个数组里。
当前正在替代孔阵列。
UPDATE:同时将sql部分移到foreach中:

foreach($users as $user){
     $shop_id = $user['id'];
     $shop_name = $user['name'];
     $total = Item::where('user_id', $shop_id)->sum('total');
     $shops[] =['Name' => $shop_name, 'total' => $total];
 }

相关问题