【发布时间】:2020-09-08 08:12:23
【问题描述】:
用户产品控制器
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'));
}
}
products_table
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');
});
}
categories_table
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');
我怎样才能获得同一类别的所有产品?因为这是我的第一个项目,所以我花更多的时间在这上面。但没有什么对我有用。谁能指导我一下?
【问题讨论】:
-
与您的问题无关,但是您的 Product 模型上的
category()关系方法不正确,应该是$this->belongsTo('App\Category', 'cat_id'),因为您的外键列称为cat_id而不是@987654330 @
标签: php laravel e-commerce