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');

如何获得同一类别的所有产品?由于这是我的第一个项目,我在这方面花费了更多的时间。但对我来说没有任何作用。有人可以指导我吗?


慕工程0101907
浏览 82回答 4
4回答

杨魅力

假设你正确设置了你的关系(但事实并非如此)您可以通过以下几种方式使用 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();

森栏

首先,你没有正确定义你们的关系。它应该是这样的: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

白衣非少年

您需要对您的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 查询。有关急切加载和延迟加载的更多信息可以在文档中找到。

回首忆惘然

你可以做类似的事情,$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);
打开App,查看更多内容
随时随地看视频慕课网APP