V
V
Vanya Huk2017-09-02 21:17:28
ORM
Vanya Huk, 2017-09-02 21:17:28

What is the correct way to write with with aggregate functions?

There are 2 tables: products and reviews .
Products store information about a product, and reviews store reviews about it.
And there is a relationship:

public function rev()
    {
       return $this -> hasMany( Review::class )-> whereVerify(1);
    }

it works, everything is fine, but, I need to count the number of reviews itself.
When I do it like this
public function rev_count()
    {
       return $this -> hasMany( Review::class )-> whereVerify(1) -> count();
    }

and output:
$product = Product::whereId(1)->first();

echo $product -> rev_count();

everything works, but I need to return the number of reviews in this way:
$product = Product::whereId(1) -> with('rev_count')->first() -> toJson();

last one throws a bug
[Symfony\Component\Debug\Exception\FatalThrowableError]     
  Call to a member function addEagerConstraints() on integer

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
miki131, 2017-09-03
@miki131

https://laravel.com/docs/5.4/eloquent-serialization...

M
Muhammad, 2017-09-04
@muhammad_97

https://laravel.com/docs/5.4/eloquent-relationships , section Counting Related Models

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question