gpt4 book ai didi

php - 拉维 | Eloquent foreach不工作

转载 作者:可可西里 更新时间:2023-11-01 00:40:13 27 4
gpt4 key购买 nike

我正在尝试从我的用户表中检索所有非管理员用户。像这样

$agents = User::where('is_admin','=', 'false')->get();

//didn't work
foreach ($agents as $agent=>$value)
{
echo "{$agent}=>{$value}"."<br>";
}

//tried dumping
dd($agents);

但它没有用,所以我尝试转储变量以检查它是否有任何结果,我现在有一个非管理员:这是输出

Collection {#219 ▼
#items: array:1 [▼
0 => User {#222 ▼
#casts: array:1 [▶]
#fillable: array:6 [▶]
#hidden: array:2 [▶]
#connection: null
#table: null
#primaryKey: "id"
#keyType: "int"
+incrementing: true
#with: []
#perPage: 15
+exists: true
+wasRecentlyCreated: false
#attributes: array:10 [▶]
#original: array:10 [▶]
#dates: []
#dateFormat: null
#appends: []
#events: []
#observables: []
#relations: []
#touches: []
+timestamps: true
#visible: []
#guarded: array:1 [▶]
#rememberTokenName: "remember_token"
}
]
}

请帮忙

最佳答案

$agents = User::where('is_admin','=', 'false')->pluck('value', 'agent'); 

foreach ($agents as $agent=>$value) {
echo "{$agent}=>{$value}"."<br>";
}

使用 pluck,您可以将对象转换为数组,因此您可以按照您希望的方式将 foreach 与 key => value 一起使用。

如果你需要访问模型的其他属性,你需要做这样的事情:

$agents = User::where('is_admin','=', 'false')->get(); 

foreach ($agents as $agent) {
echo "{$agent->id}=>{$agent->name}"."<br>";
}

这样你只需要使用 $agent-> 后跟你想要的属性。

关于php - 拉维 | Eloquent foreach不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43271110/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com