我還有一個問題。所以,這次我需要從我的控制器發送計算的數據來查看。 我有發送簡單的數據沒有問題,如:如何從Controller獲取計算的數據以查看並顯示它(laravel)?
// Controller
public function index() {
$page = Page::whereAlias('products');
$products = Product::all();
$data = compact('page', 'products');
return View::make('products', $data);
}
//View
@foreach ($products as $product)
{{ $product->title }}
@endforeach
但在我的項目,我需要計算每個產品的折扣,如果折扣日期是正確的,它顯示爲折扣商品。 同時計算此產品的評級,評論數量等。我擁有所有正確的關係和模型。
在我的項目,我有一個代碼(我認爲這是不正確的):
// Controller
public function index() {
$page = Page::whereAlias('products');
$products = Product::all();
$data = compact('page', 'products');
return View::make('products', $data);
}
//View
<?php
$discount_count = 0;
$rating_count = 0;
$reviews_count = 0;
?>
@foreach ($products as $product)
{{ $product->title }}
<?php
foreach ($product->rating as $rating) { $rating_count++; }
?>
{{ $rating_count }}
<?php
foreach ($product->reviews as $review) { $review_count++; }
?>
{{ $review_count }}
@if ($product->discount_date_start > $current_date < $discount_date_end)
{{ $product->price - $product-discount }}
{{ round($product->discount/($product->price/100)); }}% // discount in percents
@else
{{ $product->price }}
@endif
@endforeach
據我瞭解所有的計算必須在控制?但是,怎麼......? 謝謝。
我不確定您可以在模板引擎中使用PHP代碼嗎?擊敗了使用模板引擎的全部要點...並且,您應該執行控制器內部的所有邏輯並將變量傳遞給視圖。這就是控制器的用途。 –
我知道,但我不知道如何在控制器中進行計算併發送顯示它在視圖中:/也許可以在此計算中使用模型? srsly,我不知道:( – lieroes
只是把循環放在控制器中......並將數據作爲變量傳遞給視圖 –