4 回答

TA貢獻1811條經驗 獲得超6個贊
假設你正確設置了你的關系(但事實并非如此)
您可以通過以下幾種方式使用 Eloquent:
$products = Category::findOrFail($categoryId)->products;
$products = Product::where('category_id', $categoryId)->get();
$products = Product::whereHas('category', function ($query) use ($categoryId) {
? ? $q->where('id', $categoryId);
})->get();

TA貢獻1810條經驗 獲得超5個贊
首先,你沒有正確定義你們的關系。它應該是這樣的:
class Product extends Model
{
public function category()
{
return $this->belongsTo('App\Category');
}
}
class Category extends Model
{
public function products()
{
return $this->hasMany('App\Product');
}
}
然后在您的產品遷移文件中,cat_id 應重命名為category_id。這樣,您就不需要在關系上指定外鍵。
我假設您想列出屬于特定類別的所有產品。您可以使用路由模型綁定輕松地做到這一點。在這種情況下,您的路線應類似于:
Route::get('categories/{category:id}/products', [CategoryController::class, 'products']);
然后在你的控制器中:
use App\Category;
class CategoryController extends Controller
{
public function products(Category $category)
{
$category->load('products');
return view('products')->withCategory($category);
}
}
您可以在刀片視圖中訪問產品列表,如下所示:$category->products

TA貢獻1155條經驗 獲得超0個贊
您需要對您的Category模型進行調整,因為Category有很多Products。就目前而言,關系的命名并沒有反映出這一點
class Category extends Model
{
public function products()
{
return $this->hasMany('App\Product');
}
}
然后您可以通過Category模型訪問產品,如下所示。
$categories = Category::with('products')->all();
$categories->each(function($category) {
$products = $category->products;
// Dump & Die a collection of products
dd($products);
});
注意: 我已使用 with() 方法預先加載關系,這只是為了防止 n+1 查詢。有關急切加載和延遲加載的更多信息可以在文檔中找到。

TA貢獻1847條經驗 獲得超11個贊
你可以做類似的事情,
$products = product::with('categories')->get();
foreach($products as $product)
{
foreach($product->categories as $category)
{
echo $category->name;
}
}
$categories = Category::with('products')->get();
$category = Category::with('products')->find($category_id);
- 4 回答
- 0 關注
- 247 瀏覽
添加回答
舉報