user9888683
user9888683

Reputation:

What is the wrong with my code for query?

Please find below my code for get data from table

    $all_trades = FinalTrade::where('user_id', '=', $user_id)->where('market_id', '=', $market_id)->get();


      $numbers_of_entries = $all_trades->count();
      $l=0;
      foreach ($all_trades as &$value) {
          $value = $all_trades->pluck('buy_rate') * $all_trades->pluck('quantities');
          $l++;
      }


      DD($l);

my $all_trades->pluck('buy_rate')and $all_trades->pluck('quantities') has array result.. how can i multiplying and get array result?

result of $all_trades->pluck('buy_rate') in browser.

Collection {#1186 ▼
  #items: array:12 [▼
    0 => 2205
    1 => 0
    2 => 50351
    3 => 0
    4 => 40
    5 => 1000
    6 => 500
    7 => 324
    8 => 2342
    9 => 2342
    10 => 234
    11 => 555656
  ]
}

actually i am trying to multiply play two row.

Upvotes: 0

Views: 49

Answers (3)

apokryfos
apokryfos

Reputation: 40683

You might have better success if you actually multiply within the query:

 $all_trades = FinalTrade::where('user_id', '=', $user_id)
                ->where('market_id', '=', $market_id)
                ->select("*, (buy_rate*quantities) as total")
                ->get();

Then each of your entries will have the total property in addition to the actual entry so you can then do:

$all_trades->pluck('total');

Upvotes: 0

Devon Bessemer
Devon Bessemer

Reputation: 35337

Your problem is you are calling pluck on the collection in your loop instead of utilizing the item of the collection.

When you have the item itself, you don't need a collection method:

foreach ($all_trades as $item) {
    $product = $item->buy_rate * $item->quantities;
}

You'd have to utilize the $product somehow, otherwise it will just be overwritten in each iteration of the loop but I don't know what you're trying to do with the product of this multiplication problem. You most likely don't want to be assigning $value as a reference and overwriting it like you are in your question.

If you're trying to associate the product with the collection item, you can just add a new property:

foreach ($all_trades as $item) {
    $item->product = $item->buy_rate * $item->quantities;
}

Now every item in $all_trades will have a new property named product with the corresponding value. Since objects are always passed by reference, you don't need to use &$item.

Upvotes: 0

iPraxa Inc
iPraxa Inc

Reputation: 556

$all_trades = FinalTrade::where('user_id', '=', $user_id)->where('market_id', '=', $market_id)->get();

    $total =[];

  foreach ($all_trades as $value) {
      $total[] = $value->buy_rate * $value->quantities;

  }


  dd($total);

Upvotes: 1

Related Questions