我是 laravel 的新手。我想訪問products
屬于category
. 它們之間存在一對多的關系。為了獲取這些資料,我在ProductsController
named內部創建了一個函式getCtgProducts()
來完成此操作。
我知道直接從視圖中查詢資料庫是一種不好的做法,因此我在控制器中撰寫資料庫查詢并嘗試在刀片內部訪問它。
有人可以告訴我我做錯了什么嗎?
在刀片視圖中訪問控制器功能的正確方法是什么?我正在使用 Laravel 框架 v9.7.0
@foreach ($ctgs as $ctg)
<h1> $ctg->name </h1> // -- It is working. Showing the correct ctgs names
<div class=container>
@if (isset($products))
@foreach ({{ App\Http\Controllers\ProductsController::getCtgProducts($ctg->id) }} as $product)
<h1> $product->name </h1>
@endforeach
@endif
</div>
@endforeach
ProductsController
班級
<?php
namespace App\Http\Controllers;
use App\Models\Ctg;
use App\Models\Product;
class ProductsController extends Controller
{
public function index(Request $request)
{
$products = Product::all();
$ctgs = Ctg::all();
return view('ui\welcome', compact('products', 'ctgs'));
}
public static function getCtgProducts(){
$ctgProducts = DB::table('products')->where('ctg_id', $ctgId);
return $ctgProducts;
}
}
uj5u.com熱心網友回復:
從刀片呼叫控制器是不好的做法,將您的 getCtgProducts() 方法邏輯移動到Category Model:
public function getCtgProducts(){
$ctgProducts = DB::table('products')
->where('ctg_id', $this->id)->get();
return $ctgProducts;
}
刀片檔案:
@foreach ($ctgs as $ctg)
<h1> $ctg->name </h1> // -- It is working. Showing the correct ctgs names
<div class=container>
@foreach ($ctg->getCtgProducts() as $product)
<h1> $product->name </h1>
@endforeach
</div>
@endforeach
更好的方法:由于類別模型中存在一對多關系,您應該有一個關系方法:
public function products() {
return $this->hasMany(Product::class);
}
刀:
@foreach ($ctgs as $ctg)
<h1> $ctg->name </h1> // -- It
is working. Showing the correct ctgs
names
<div class=container>
@foreach ($ctg->products as
$product)
<h1> $product->name </h1>
@endforeach
</div>
@endforeach
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/465356.html
標籤:php mysql 拉拉维尔 控制器 laravel-刀片