简体   繁体   中英

How to select the total downloads of each promotion that I have in my database, with laravel ORM eloquent 5.8?

Using laravel, I need to show in a graph the number of times a promotion is redeemed. I can get the promotions published by each user that starts session, but I need you to put that data in a graph. I would greatly appreciate your help.


Current Code:

    $nombres = Promociones::where('user_id',Auth::user()->id)->pluck('nombre_promocion', 'id');

    $promociones = [];
    $descargadas = [];

    foreach ($nombres as $key => $val)
    {
        $promociones[] = $val;
        $descargadas[] = Promociones::where('user_id',$key)->count();
    }  

    $chart = new UserPromociones;
    $chart->title(' Promociones publicadas ');
    $chart->labels($promociones);
    $chart->dataset('Numero de promociones','bar', ($descargadas));
    $chart->dataset('Total de promociones publicadas = '.$total_promociones,'bar',[]);

Desired Graph Output:

该图

i think the problem is in this line

$descargadas[] = Promociones::where('user_id',$key)->count();

as you only look for user_id who match the array index!!

it should be like

$descargadas[] = Promociones::where('user_id',$val)->count();

or

$descargadas[] = Promociones::where('user_id',$val->id)->count();

and even if this work , that is not the best way, the worst thing to do is to but and database query in loop, that is horrible

if the data is not that big , you can do something like that before foreach

$promociones = collect(Promociones::all()->toArray());

this will extract the model to a collection, then any where clause will be a search in a collection and require no database query for each time.

 $promociones = collect(Promociones::all()->toArray());

 foreach ($nombres as $key => $val)
    {
        $promociones[] = $val;
        $descargadas[] = $promociones->where('user_id',$val->any_filed)->count();
    }  

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