на данный момент я создаю ссылку на свой продукт на мою категорию прямо из моего кода в моем семени, делая ->categories()->attach(1)
в конце каждого продукта.
Из моей базы данных я могу создать продукт но я не могу связать их внешним ключом с категорией, которая уже находится в category_product_table
.
У меня есть 3 таблицы: products
, categories
и category_product
.
2020_04_09_073846_create_products_table
public function up()
{
Schema::create('products', function (Blueprint $table) {
$table->increments('id');
$table->integer('category_id')->unsigned()->index();
$table->foreign('category_id')->references('id')->on('categories')->onDelete('cascade');
$table->string('name');
$table->string('slug');
$table->string('category');
$table->string('description');
$table->string('releaseDate');
$table->float('price');
$table->timestamps();
});
}
ProductSeeder
<?php
use Illuminate\Database\Seeder;
use App\Product;
class ProductSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
Product::create([
'name' => 'Halo 5',
'slug' => 'halo-5',
'category_id' => '1',
'category' => 'Xbox One',
'description' => "Halo 5: Guardians sur Xbox One est un FPS mettant en scène les aventures du Master Chief et d'un nouveau personnage, le Spartan Jameson Locke. ",
'releaseDate' => '27 octobre 2015',
'price' => '54.99'
]);
2020_05_02_201337_create_categories_table
_ 1019 *
Таблица_категорий_категории *1018*_ 1019 * *1020* Таблица_категорий *1018*_ 1019 * *1020* Таблица_категорий *1020*
public function up()
{
Schema::create('category_product', function (Blueprint $table) {
$table->increments('id');
$table->integer('product_id')->unsigned()->nullable();
$table->foreign('product_id')->references('id')->on('products')->onDelete('cascade');
$table->integer('category_id')->unsigned()->nullable();
$table->foreign('category_id')->references('id')->on('categories')->onDelete('cascade');
$table->timestamps();
});
}
Продукт. php
class Product extends Model
{
public function categories()
{
return $this->AsOne('App\Category');
}
}
Категория. php
class Category extends Model
{
public function products()
{
return $this->belongsToMany('App\Product');
}
}
HomeController
public function public(){
if (request()->category) {
$home = Product::with('categories')->whereHas('categories', function ($query){
$query->where('slug', request()->category);
})->get();
$categories = Category::all();
$categoryName = $categories->where('slug', request()->category)->first()->name;
} else {
$home = Product::inRandomOrder()->paginate(9);
$categories = Category::all();
$categoryName = 'Featured';
}
return view('home.index')->with([
'home' => $home,
'categories' => $categories,
'categoryName' => $categoryName,
'mode' => 'public'
]);
Если кто-то может мне помочь, спасибо за помощь!