我是 Laravel 的新手。我用這個關鍵字用谷歌搜索過,但沒有運氣。我用的是Laravel 8。目前我需要查看每個類別的資料,所以在blade上會是這樣:
cat A
product A1 <img src=(get from thumbnail)>
product A2 <img src=(get from thumbnail)>
cat B
product B1 <img src=(get from thumbnail)>
product B2 <img src=(get from thumbnail)>
etc...
目前我的控制器是:
$categories = DB::table('tbl_categories')
->orderBy('name')
->get();
foreach($categories as $key) {
$data = DB::table('tbl_product')
->where('status','Enable')
->where('category_id',$key->id)
->get();
}
$thumbnail = DB::table('tbl_thumbnails')
->where('product_id',$data[0]->id)
->get();
return view('/products', ['categories' => $categories, 'data' => $data, 'thumbnail' => $thumbnail]);
在我的刀片中:
@foreach($categories as $discover_category)
<div>
@foreach($data as $discover)
@foreach($thumbnail as $a)
<!-- product name and thumbnail in here-->
@endif
@endif
</div>
@endif
但結果現在只顯示最后一個 category_id。請幫忙。GBU。
uj5u.com熱心網友回復:
您需要使用first()來獲得這樣的單個值
foreach($categories as $category) {
$products = DB::table('tbl_product')
->where('status','Enable')
->where('category_id',$category->id)
->get();
foreach ($products as $product) {
$thumbnail = DB::table('tbl_thumbnails')
->where('product_id',$product->id)
->first();
// assign value to $product
$product->thumbnail = $thumbnail;
}
// assign value to $category
$category->products = $products;
}
那么在視圖中你可以使用像
@foreach($categories as $category)
<div>
@foreach($category->products as $product)
<div>
<p>{{$product->name}}</p>
<p>{{$product->thumbnail->id}}</p>
</div>
<!-- product name and thumbnail in here-->
@endif
</div>
@endif
uj5u.com熱心網友回復:
您可以使用 Eloquent ORM,只需在您的類別模型上使用這種代碼,例如:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Category extends Model
{
/**
* Get the products for the category.
*/
public function products()
{
return $this->hasMany(Product::class);
}
}
在控制器上
$categories = Category::all();
return view('products', ['categories' => $categories]);
在刀片上喜歡
@foreach($categories as $category)
<div>
<div>{{ $category->name }}</div>
@foreach($category->products as $products) // here this products object called form model
@foreach($products as $product)
<!-- product name and thumbnail in here-->
@endforreach
@endforreach
</div>
@endforeach
筆記
注意:您必須完美地處理產品表和類別表之間的關系。產品表必須有一列名為
category_id
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/364639.html
