【发布时间】:2018-08-18 10:56:49
【问题描述】:
所以我在产品和产品类别之间有这种关系,一个产品属于一个类别,一个类别可以包含许多产品,问题是我想通过名称而不是使用 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');
}
}
有什么帮助吗?
【问题讨论】: