首页 > 解决方案 > 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');

如何获取同一类别的所有产品?因为这是我的第一个项目,所以我花更多的时间在这上面。但没有什么对我有用。有人可以指导我吗?

标签: phplaravele-commerce

解决方案


假设您正确设置了您的关系(事实并非如此)

你有几种使用 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

Laravel 7.x Docs - Eloquent - 关系 - 关系方法与动态属性

Laravel 7.x Docs - Eloquent - 关系 - 查询关系的存在 whereHas


推荐阅读