首页 > 解决方案 > 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;
    }
}

标签: phplaravel

解决方案


发生这种情况是因为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);
    });
}

推荐阅读