sync subcategory in laravel - ajax

i made products and categories and sub categories
when i do sync them , product and category save in the category_prodcts.
but sub category shows a error message :
SQLSTATE[HY000]: General error: 1364 Field 'subcategory_id' doesn't have a default value (SQL: insert into `category_products` (`category_id`, `product_id`) values (1, 1))
and these are my codes :
productController:
$data->cats()->sync($request->cats,false);
$data->subcategory()->sync($request->subcategory,false);
Product Model:
public function CATS(){
return $this->belongsToMany(Category::class, 'category_products',
'product_id', 'category_id');
}
public function subcategory()
{
return $this->belongsToMany(SubCategory::class,
'category_products','subcategory_id','category_id' );
}
subcategory Model:
public function products()
{
return $this->belongsToMany(Products::class,'subcategory_products',
'category_id','subcategory_id');
}
public function category(){
return $this->belongsToMany(Category::class)->withTimestamps();
}
category model:
public function subcategory()
{
return $this->belongsToMany(Subcategory::class,
'category_subcategory', 'category_id', 'subcategory_id' );
}
category_product database:
$table->unsignedBigInteger('product_id');
$table->unsignedBigInteger('category_id');
$table->unsignedBigInteger('subcategory_id');
$table->foreign('product_id')
->references('id')
->on('products')
->onDelete('cascade');
$table->foreign('category_id')
->references('id')
->on('categories')
->onDelete('cascade');
$table->foreign('subcategory_id')
->references('id')
->on('categories')
->onDelete('cascade');
$table->primary(['category_id','product_id','subcategory_id']);
enter code here
thanks for your help

Related

Laravel eloquent relations not working completely

I've a payment gateway, I want to access the product items after returning, so I created several tables Payments, Orders, OrderItems and configured the relationships between them.
Each Payment is for one Order and each Order contains several OrderItem and each OrderItem contains one product. Now I want to access each Product through an object of the Payment Model, which returns the following error.
Illuminate\Database\QueryException SQLSTATE[42S22]: Column not found:
1054 Unknown column 'orders.order_item_id' in 'field list' (SQL:
select products.*, orders.order_item_id as laravel_through_key
from products inner join orders on orders.id =
products.order_id where orders.order_item_id = 68 limit 1)
$product_order_item = $payment->order->order_items->map(function ($order_item) {
dd($order_item->product);
});
Payment Model:
protected $table = "payments";
protected $guarded = [];
public function order() {
return $this->belongsTo(Order::class);
}
Order Model:
protected $table = "orders";
protected $guarded = [];
public function payment() {
return $this->hasOne(Payment::class);
}
public function order_items() {
return $this->hasMany(OrderItem::class);
}
OrderItem Model:
protected $table = "order_items";
protected $guarded = [];
public function order() {
return $this->belongsTo(Order::class);
}
public function product() {
return $this->hasOneThrough(Product::class, Order::class);
}
Product Model:
protected $table = "products";
protected $guarded = [];
public function order_items() {
return $this->belongsToMany(OrderItem::class);
}
That is migrations:
Schema::create('orders', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('user_id');
$table->foreign('user_id')->references('id')->on('users')->onDelete('CASCADE');
$table->unsignedInteger('amount');
$table->unsignedInteger('res_code');
$table->enum('status', ['paid', 'unpaid']);
$table->timestamps();
});
=====================================================
Schema::create('order_items', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('order_id');
$table->foreign('order_id')->references('id')->on('orders')->onDelete('CASCADE');
$table->unsignedBigInteger('product_id');
$table->foreign('product_id')->references('id')->on('products')->onDelete('CASCADE');
$table->unsignedInteger('price');
$table->timestamps();
});
===========================================================
Schema::create('payments', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('order_id');
$table->foreign('order_id')->references('id')->on('orders')->onDelete('CASCADE');
$table->enum('status', ['paid', 'unpaid']);
$table->unsignedInteger('ref_id');
$table->unsignedInteger('res_id');
$table->enum('gateway', ['idpay', 'zarinpal']);
$table->timestamps();
});
what is the problem?
Thanks in advance...
You should use belongsTo for the product relationship of OrderItem Model
OrderItem Model:
public function product() {
return $this->belongsTo(Product::class);
}
https://laravel.com/docs/8.x/eloquent-relationships#one-to-many-inverse
And hasMany for the order_items relationship of Product Model
Product Model:
public function order_items() {
return $this->hasMany(OrderItem::class);
}
https://laravel.com/docs/8.x/eloquent-relationships#one-to-many

how to make filter for food by category and subcategory , and once i press on any category i get its food dishes

using these tables I need to make category filter
Food Table: Migration
$table->bigIncrements('id');
$table->unsignedBigInteger('category_id')->nullable();
$table->unsignedBigInteger('image_id')->nullable();
$table->string('name')
$table->float('price',9,2)->default(0);
$table->float('offer_price',9,2)->nullable()->default(0);
$table->boolean('visible')->default(0);
$table->timestamps();
categories table: Migration
Schema::create('categories', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedBigInteger('parent_id')->nullable();
$table->unsignedBigInteger('image_id')->nullable();
$table->boolean('visible')->default(0);
$table->timestamps();
});
Food Model relation
public function category()
{
return $this->belongsTo(Category::class, 'category_id')->withDefault();
}
Category Model relation
public function food()
{
return $this->hasMany(Food::class)->orWhereIn('category_id' , $this->subcategory()->pluck('id')->toArray())->visible();
}
public function subcategory()
{
return $this->hasMany(self::class, 'parent_id', 'id');
}
````[When clicking on any category it should show food, that related to the category I clicked on ][1]
[1]: https://i.stack.imgur.com/zpVb8.png
you can simply do this in your controller
public function index(Request $request)
{
$query=Food::query();
// filter by categoryid
if ($request->has('category_id')){
$query->whereCategoryId($request->get('category_id'));
}`
// sort and exexute
$query=$query->orderBy('id','DESC');
return response($query);
}

Laravel eloquent relationships hasMany two foreign keys error

I use Laravel 7.2 and I've 2 models:
User
public function orders()
{
if($this->hasRole("seller")) {
return $this->hasMany('App\Models\Order', 'seller_id', 'id');
} else if($this->hasRole("client")) {
return $this->hasMany('App\Models\Order', 'user_id', 'id');
}
}
Order
Migration:
Schema::create('orders', function (Blueprint $table) {
$table->id();
$table->boolean('status')->default(false);
$table->text('description')->nullable();
$table->unsignedBigInteger('user_id');
$table->foreign('user_id')
->references('id')
->on('users')
->onDelete('cascade');
$table->unsignedBigInteger('seller_id');
$table->foreign('seller_id')
->references('id')
->on('users')
->onDelete('cascade');
$table->timestamps();
$table->softDeletes();
});
Code:
public function user()
{
return $this->belongsTo('App\Models\User', 'user_id');
}
public function seller()
{
return $this->belongsTo('App\Models\User', 'seller_id');
}
Now in my case users has two roles seller or client. But when I try get user orders laravel return me error message:
Call to a member function addEagerConstraints() on null
Or when I try get custom order user or seller related data also return same error message.
Where I've any error or I've create relationships incorrectly?
This occurs because the condition in the relation here:
public function orders()
{
if($this->hasRole("seller")) {
return $this->hasMany('App\Models\Order', 'seller_id', 'id');
} else if($this->hasRole("client")) {
return $this->hasMany('App\Models\Order', 'user_id', 'id');
}
}
Imagine users who has neither roles 'seller' or 'client' then Null will be returned and that is exactly the issue.
I recommend you to split the method orders into two methods sellerOrders and clientOrders.

Empty array trying to get all the review of product with the product id in the review table

I'm trying to get the review of a product by the product Id in the review table but i do get an empty array or nothing
this are my code.
public function index(Product $product)
{
return $product->reviews;
}
public function product()
{
return $this->belongsTo('App\Model\Product');
}
public function reviews(){
return $this->hasMany(Review::class);
}
migration code
ReviewController
public function up()
{
Schema::create('reviews', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('customer');
$table->integer('star');
$table->text('review');
$table->unsignedBigInteger('product_id')->index();
$table->foreign('product_id')->references('id')->on('products')->onDelete('cascade');
$table->timestamps();
});
}
Try this way
$product->with('reviews');

How to access the values of a foreign key of another table using laravel

I created a custom pivot model which is SectionSubject that have an id, section_id and subject_id. I want now to access the other values related to the section_id. Here is my Sectionsubject model and section_subject table:
SectionSubject.php
class SectionSubject extends Model
{
protected $table = 'section_subject';
public function students()
{
return $this->belongsToMany(Student::class, 'section_subject_student','section_subject_id'
)->withTimestamps();
}
public function assignStudents(Student $student)
{
return $this->students()->save($student);
}
}
create_section_subject.php
Schema::create('section_subject', function (Blueprint $table) {
$table->increments('id');
$table->integer('section_id')->unsigned();
$table->integer('subject_id')->unsigned();
$table->string('schedule')->unique();
$table->string('room_no');
$table->foreign('section_id')
->references('id')
->on('sections')
->onDelete('cascade');
$table->foreign('subject_id')
->references('id')
->on('subjects')
->onDelete('cascade');
});
Now I want to fetch those values and place it on my ReservationController. I tried to use one to many relationship but it seems not working.
class ReservationController extends Controller
{
public function index()
{
$sectionSubject = SectionSubject::find(1);
//code here
return view('reservation.form', compact('sectionSubject');
}
}
you can fetch relationship by doing this
$sectionSubject = SectionSubject::with('students')->find(1);
//print your variable
echo "<pre>";
print_r($sectionSubject->toArray());
echo "</pre>";
you will find the related table data

Resources