php - Laravel Eloquent 如何根据类别 id 获取所有产品
问题描述
用户产品控制器
class UserProductsController extends Controller
{
public function index()
{
$products = Product::get();
return view ('products')->with(compact('products'));
}
public function product_categories()
{
$categories = Category::all();
return view ('categories')->with(compact('categories'));
}
}
产品表
public function up()
{
Schema::create('products', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('prod_name');
$table->string('prod_brand')->nullable();
$table->unsignedBigInteger('cat_id');
$table->string('prod_image_path')->nullable();
$table->timestamps();
$table->foreign('cat_id')
->references('id')
->on('categories')
->onDelete('cascade');
});
}
类别表
public function up()
{
Schema::create('categories', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('cat_name');
$table->string('cat_image_path')->nullable();
$table->string('cat_description')->nullable();
$table->timestamps();
});
}
产品型号
class Product extends Model
{
public function category()
{
return $this->belongsTo('App\Category','category_id');
}
}
类别模型
class Category extends Model
{
public function category()
{
return $this->hasMany('App\Product');
}
}
我的路线是
Route::get('/All_Products', 'UserProductsController@index')->name('All_Products');
Route::get('/product_categories', 'UserProductsController@product_categories')->name('categories');
如何获取同一类别的所有产品?因为这是我的第一个项目,所以我花更多的时间在这上面。但没有什么对我有用。有人可以指导我吗?
解决方案
假设您正确设置了您的关系(事实并非如此)
你有几种使用 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();
列举几个。
Laravel 7.x 文档 - Eloquent - 检索单个模型/聚合 findOrFail
推荐阅读
- dart - Dart 中的静态函数 - 只调用一次
- c++ - 如何检查 char 数组是否组合成某个连续的字符列表?
- java - 如何访问在另一种方法中创建的对象
- python - GitPython - git add - 错误 - 文件无法识别
- tensorflow - 仅优化使用 TensorFlow Estimator API 的模型的某些变量
- javascript - 如何删除和显示选择选项子类别
- postgresql - 来自本地 PostgreSQL 的 Azure 数据工厂
- excel - 使用 VBA 在 Outlook 中设置约会
- angular - 在剑道网格 ui 中获取过滤器值
- java - 如何从外部文件夹或外部 jar 加载 Evolutions 脚本(数据库迁移脚本)?