为了账号安全,请及时绑定邮箱和手机立即绑定

Laravel Eloquent如何根据类别id获取所有产品

Laravel Eloquent如何根据类别id获取所有产品

PHP
慕工程0101907 2023-12-15 17:05:05
用户产品控制器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');如何获得同一类别的所有产品?由于这是我的第一个项目,我在这方面花费了更多的时间。但对我来说没有任何作用。有人可以指导我吗?
查看完整描述

4 回答

?
杨魅力

TA贡献1811条经验 获得超5个赞

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


您可以通过以下几种方式使用 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();


查看完整回答
反对 回复 2023-12-15
?
森栏

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


查看完整回答
反对 回复 2023-12-15
?
白衣非少年

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


查看完整回答
反对 回复 2023-12-15
?
回首忆惘然

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


查看完整回答
反对 回复 2023-12-15
  • 4 回答
  • 0 关注
  • 77 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信