简体   繁体   中英

Foreach with eloquent in laravel

I'm trying to loop through the items using eloquent in laravel but I'm getting 0 . Please see my code below.

Model

Class Store{

    public function products(){
        return $this->hasMany('App\Product');
    }

}

Controller

$products_count = 0;

foreach($store->products() as $product)
{
   if($product->status == 1)
   {
     $products_count++;
   }
}

dd($products_count);

Note: I have data in my database.

You can also use withCount method something like that

Controller

$stores = Store::withCount('products')->get();
or
$store = Store::where('id', 1)->withCount('products')->first();

WithCount on the particular status

$stores = Store::withCount(['products' => function ($query) {
                            $query->where('status', 1);
                          }
                    ])
                    ->get();

ref: withcount on relationship

That's because $store->products() returns an eloquent collection which doesn't contain the data from the database yet. You need to do $store->products instead.

If you need to get the count from the database then use

$store->products()->where('status', 1)->count()

With the function-annotation (ie products() ) you are retrieving the \\Illuminate\\Database\\Eloquent\\Builder -instance, not the actual Eloquent-collection.

Instead, you would have to use $store->products – then you will get retrieve the related collection.

在Laravel中, $store->products() store- $store->products()使您可以访问QueryBuilder实例,而是使用Laravel的$store->products store- $store->products ,该方法可以加载QueryBuilder并自动检索集合,并且很容易进行优化。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM