draw134
draw134

Reputation: 1187

Laravel add query results via append in model

I want to append a specific column in my model which is returns_count it is based from a query. But when I executed it it gives me the wrong result. It has the same value from all of the results. Can someone help me with this. I think I almost got it. Thanks

Model

   protected $appends = [
        'returns_count'
    ];
    public function getReturnsCountAttribute(){
        $users = DB::table('users_mws')
            ->select('users_mws.*')
            ->join('users','users.id','=','users_mws.user_id')
            ->where('users.status','<>','Dumped2')
            ->orderBy('users_mws.mws_name','asc')
            ->get();
        $clientCount = array();
        foreach ($users as $data){
            $returnCount = AdminMwsReturnsEligiblesData::where('users_mws_id', $data->id)->count();
            $clientCount[] = $returnCount;
            return $clientCount;
        }
    }

Result (it must be different per result) i got 191 per result which is not correct

 {
    "id": 153,
    "user_id": 216,
    "mws_name": "1 Body",
    "oem_alias": null,
    "oem_mws_id": null,
    "user_type": "user",
    "returns_count": [
      191
    ]
  },
  {
    "id": 145,
    "user_id": 211,
    "mws_name": "Activewear",
    "oem_alias": null,
    "oem_mws_id": null,
    "user_type": "user",
    "returns_count": [
      191
    ]
  },

The count result in this query

  $clientCount = array();
        foreach ($usersMws as $data){
            $returnCount = AdminMwsReturnsEligiblesData::where('users_mws_id', $data->id)->count();
            $clientCount[] = $returnCount;
            
        }
        dd($clientCount);
  0 => 191
  1 => 16
  2 => 6
  3 => 3
  4 => 25
  5 => 4
  6 => 35
  7 => 0
  8 => 115
  9 => 1
  10 => 18
  11 => 68
  12 => 14
  13 => 0
  14 => 36
  15 => 32
  16 => 147
  17 => 8
 ...

Upvotes: 1

Views: 1802

Answers (1)

AbingPj
AbingPj

Reputation: 659

To get attribute data, avoid using for loop. it may cause lag.

try this code. i separate the query into the scope. and appends must be direct.

protected $appends = [
        'returns_count'
    ];

 public function getReturnsCountAttribute(){
        return AdminMwsReturnsEligiblesData::where('users_mws_id', $this->id)->count();
    }


Scoped:

public function scopeReturnCount($query)
    {
        $query->select('users_mws.*')->join(
            'users',
            'users_mws.user_id',
            '=',
            'users.id'
        )
        ->where('users.status','<>','Dumped2')
        ->orderBy('users_mws.mws_name','asc');

        return $query;
    }

Controller:

$users = UsersMws::returnCount()->get();

Model scoped function can also carry the appends data.

Upvotes: 1

Related Questions