我是 Laravel 新手。我正在尝试使用 HasTo 关系。我的数据库中有两张表。一张是产品表,另一张是类别表。我使用表单添加产品。表单中有一个选择选项部分。在此部分中,我从类别表中为产品选择一个类别。问题是,当我选择一个类别时,我想获取该类别的 ID 并将其添加到产品表中的 categoryId 列。然后,当我发布产品时,我想访问产品表中的 categoryId 部分并获取类别表中匹配的类别,但我无法成功。这是我的表单:
<form action="{{ route('product.store') }}" method="post" enctype="multipart/form-data">
@csrf
<div class="form-group mb-3">
<label>Name</label>
<input
name="productName"
type="text"
class="form-control" />
</div>
<div class="form-group mb-3">
<label>Description</label>
<textarea name="productDescription" class="form-control" rows="3"></textarea>
</div>
<div class="form-group mb-3">
<label>Price</label>
<input name="productPrice" type="number" class="form-control" />
</div>
<div class="form-group mb-3">
<label>Category</label>
<input name="categoryId" type="number" class="form-control" />
<select class="custom-select tm-select-accounts form-control" name="categoryId">
<option>Choose a Category</option>
@foreach($getCategory as $category)
<option value="{{ $category->id }}">{{ $category->categoryName}}</option>
@endforeach
</select>
</div>
</div>
<div class="col-12">
<button type="submit" class="btn btn-primary btn-block text-uppercase">Add Product</button>
</div>
</form>
这是我发布产品时的表格:前3个td标签正常工作。我无法获取与categoryId匹配的categoryName,因此我直接发布了该ID。
<tbody>
@foreach ($product as $item)
<tr>
<th scope="row">
<input type="checkbox" />
</th>
<td class="tm-product-name">{{ $item->productName }}</td>
<td>{{ $item->productPrice }}</td>
<td>{{ $item->productDescription }}</td>
<td>{{ $item->categoryId }}</td>
<td>
<a href="{{ route('product.edit', $item->id) }}">
<i class="fas fa-3x fa-edit"></i>
</a>
</td>
<td class="text-right">
<form method="post" action="{{ route('product.destroy', $item->id) }}">
@method('delete')
@csrf
<button type="submit" class="btn btn-danger btn-sm show_confirm" id="deletebutton">Delete Product</button>
</form>
</td>
</tr>
@endforeach
</tbody>
产品控制器:
public function index()
{
$product = Page::all();
return view('admin.pages.products', compact('product'));
}
/**
* Show the form for creating a new resource.
*/
public function create()
{
$data['getCategory'] = Category::get();
return view('admin.pages.add_product', $data);
}
/**
* Store a newly created resource in storage.
*/
public function store(Request $request)
{
$request->validate([
'productName' => ['required','string','max:255'],
'productDescription' => ['required','string'],
'productPrice' => ['nullable','numeric'],
'categoryId' => ['required'],
]);
$product = new Page();
$product->productName = $request->productName;
$product->productDescription = $request->productDescription;
$product->productPrice = $request->productPrice;
$product->categoryId = $request->categoryId;
$product->save();
return redirect()->route('admin')->with('success', 'Ürün başarıyla eklendi');
}
页面模型:
class Page extends Model
{
protected $table = 'products';
protected $fillable = [
'productName',
'productDescription',
'productPrice',
'productImage',
'categoryId'
];
public function products()
{
return $this->belongsTo(Category::class);
}
}
类别型号:
class Category extends Model
{
protected $table = 'category';
protected $fillable = [
'categoryName',
];
public function productCategories()
{
return $this->hasMany(Page::class);
}
}
我已经设法链接数据库中的两个表,但无法使用产品表中的类别 ID 获取类别表中的类别名称。
忘记页面模型,它没有意义:你应该在代码中重命名某些东西。
从模型开始:
我建议阅读 Laravel 文档。
categories
看来您正在 Laravel 中建立和之间的一对多关系products
,其中每个产品都属于一个类别。要实现此目的并显示与每个产品关联的类别名称,请按照以下步骤操作:定义模型中的关系:
产品型号(
Product.php
):复制编辑
public function category() { return $this->belongsTo(Category::class, 'categoryId'); }
这定义了一种反向的一对多关系,表明每种产品属于一个类别。
类别模型(
Category.php
):复制编辑
public function products() { return $this->hasMany(Product::class, 'categoryId'); }
这建立了一对多的关系,表明一个类别可以有多个产品。
调整添加产品的表单:
确保表单
<select>
元素允许用户选择产品类别:复制编辑
<div class="form-group mb-3"> <label>Category</label> <select class="custom-select tm-select-accounts form-control" name="categoryId"> <option value="">Choose a Category</option> @foreach($getCategory as $category) <option value="{{ $category->id }}">{{ $category->categoryName }}</option> @endforeach </select> </div>
此设置确保当选择一个类别时,它会像表单提交
id
一样发送。categoryId
修改控制器以处理表单提交:
在处理表单提交的控制器方法中,验证并保存传入的数据:
复制编辑
public function store(Request $request) { $validatedData = $request->validate([ 'productName' => 'required|string|max:255', 'productDescription' => 'nullable|string', 'productPrice' => 'required|numeric', 'categoryId' => 'required|exists:categories,id', ]); Product::create($validatedData); return redirect()->route('product.index')->with('success', 'Product added successfully.'); }
这可确保在创建产品之前
categoryId
所提供的信息存在于表中。categories
显示产品及其类别:
检索要显示的产品时,预先加载
category
关系以尽量减少数据库查询:复制编辑
$products = Product::with('category')->get();
然后,在您的视图中显示与每个产品相关的类别名称:
复制编辑
<tbody> @foreach ($products as $item) <tr> <td>{{ $item->productName }}</td> <td>{{ $item->productPrice }}</td> <td>{{ $item->productDescription }}</td> <td>{{ $item->category ? $item->category->categoryName : 'Uncategorized' }}</td> <!-- Additional columns as needed --> </tr> @endforeach </tbody>
此方法检查产品是否有关联类别并显示其名称。如果没有,则显示“未分类”。