Answer the question
In order to leave comments, you need to log in
Product = 1 category, category = many Laravel 5.3 products?
I figured out the joins 1:1, 10:10.
But 1:10 where 10:1 is something tight.
My example code:
// класс продукта
public function productCategory()
{
return $this->belongsTo('App\Category');
}
// класс категории
public function categoryProducts(){
return $this->hasMany('App\Product');
}
// это вытянет все продукты, где category_id == текущий category_id
// Однако, обратной это не работет, dd($product->productCategory) в продукте, вернет null
Answer the question
In order to leave comments, you need to log in
In the case of categories, it is important to give the opportunity to link a product to several categories.
Start with the following code:
Migration
Schema::create('product_category', function (Blueprint $table) {
$table->integer('product_id');
$table->integer('category_id');
});
return $this->belongsToMany('App\Category', 'product_category', 'product_id', 'category_id');
public function productCategory()
{
return $this->hasOne('App\Category');
}
public function categoryProducts(){
return $this->hasMany('App\Product');
}
// В котроллерах:
$category = Category::findOrFail(1);
dd($category->categoryProducts());
$product = Product::findOrFail(1);
dd($category->productCategory());
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question