Laravel:按类别名称而不是ID检索表结果

时间:2018-08-18 01:58:26

标签: php laravel eloquent

所以我在产品和产品类别之间有这种关系,一个产品属于一个类别,一个类别可以容纳许多产品,问题是我想按名称而不是使用id检索属于该产品类别的所有产品。

有些相似之处?

public function index()
    {
        Product::where(productcategory->name, 'Starters')->get();
    }

这些是我的迁移:

//CREATE PRODUCTS TABLE
        Schema::create('products', function (Blueprint $table) {
            $table->increments('id');
            $table->unsignedInteger('productcategory_id')->index();
            $table->foreign('productcategory_id')->references('id')->on('productcategories')->onDelete('cascade');
            $table->string('name');
            $table->string('description')->nullable();
            $table->string('image')->nullable();
            $table->boolean('available')->default(true);
            $table->string('half');
            $table->string('full');
            $table->timestamps();
        });
        
        
        
        
        //CREATE PRODUCT CATEGORIES TABLE
        Schema::create('productcategories', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->string('description')->nullable();
            $table->string('image')->nullable();
            $table->timestamps();
        });
        DB::table('productcategories')->insert([
            'name' => 'Starters'),
        ]);
        DB::table('productcategories')->insert([
            'name' => 'Salads'),
        ]);
        DB::table('productcategories')->insert([
            'name' => 'Soups'),
        ]);

还有我的模特:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class ProductCategory extends Model
{
    protected $table = 'productcategories';
    
    
    
    
    public function products()
    {
        return $this->HasMany('App\Product');
    }
}

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Product extends Model
{
    protected $table = 'products';
    
    
    
    
    public function orders()
    {
        return $this->belongsToMany('App\Order');
    }
    
    
    
    
    public function productcategory()
    {
        return $this->belongsTo('App\ProductCategory');
    }
}

有帮助吗?

1 个答案:

答案 0 :(得分:0)

从产品类别开始并获取其产品:

$products = ProductCategory::where('name', 'Starters')->first()->products;

或使用whereHas()

$products = Product::whereHas('productcategory', function($query) {
    $query->where('name', 'Starters');
})->get();