【发布时间】:2021-02-03 07:51:26
【问题描述】:
我想在我的模型中附加一个特定的列 returns_count 它是基于查询的。但是当我执行它时,它给了我错误的结果。它在所有结果中具有相同的值。有人可以帮我弄这个吗。我想我几乎明白了。谢谢
型号
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;
}
}
结果(每个结果必须不同)我得到 191 每个结果,这是不正确的
{
"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
]
},
本次查询的计数结果
$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
...
【问题讨论】:
-
return $clientCount;看起来不正确,可能会在第一个循环后停止。 -
我看到了@NigelRen 先生,但是当我把它放在循环之外时,它不会再运行它会抛出最多 60 秒的执行时间。我需要做什么?
-
你使用的是什么版本的 Laravel?
-
它的
"laravel/framework": "^6.0",先生@Rwd -
正如 Nigel Ren 上面提到的,移动
return语句,使其位于foreach循环下方。
标签: php mysql laravel eloquent