php - Having difficulties displaying all content on my wishlist table
问题描述
I am trying to retrieve the data on my wishlist table, for a particular user, so far it only retrieves the first data on the table, just returning one array instead of the three in the table with same user id
public function getWishlistByUserId($id){
$wishlists = Wishlist::where('userId', $id)->get();
foreach($wishlists as $wishlist){
$products = Product::where('id', $wishlist->productId)->get();
return $products;
}
}
解决方案
发生这种情况是因为foreach
循环在第一次迭代期间返回了一个值。将您的return
语句放在循环之外。你也可以通过利用关系来提高你的表现。
一个例子可能是:
// Product.php
public function wishlists()
{
return $this->hasMany(Wishlist::class);
}
// Your method
public function getWishlistByUserId($id)
{
return Product::whereHas('wishlists', function ($query) use ($id) {
$query->where('userId', $id);
});
}
推荐阅读
- android - 无法启动 Appium 设置应用程序:5071 毫秒后未满足条件。超时
- html - 结构指令传递 Html Elements 属性值
- apache-kafka - 使用 SLF4j 为 Apache Beam 和 Kafka 客户端配置日志记录
- rust - link-arg 没有将编译器选项传递给 rustc
- laravel - 尝试从多对多关系 laravel 获取数据时,在字段列表中显示列“user_id”不明确
- reactjs - Reactjs - 我可以在我网站的所有页面中使用来自 AWS Amplify 的 Auth.authenticatedUser 函数吗?
- bash - 多个文件的 Gnuplot 脚本
- tensorflow - 通过 keras 和张量流的 LPR/ANPR
- python - Python 问题在脚本中导入我的文件(不在控制台中)
- powershell - PowerShell:从 API 响应中检索特定单词并编译成 HTML 表