Reputation: 109
I have a product model with versioned data and I got a category model that can have one or many products. When I want to delete a category the code has to check if there are products related to the category. How to define the relation so that it goes to the products_version
table to check if the category_id
exists here before deleting it?
Here is my product model:
use Versionable, SoftDeletes;
protected $fillable = ['product_name', 'supplier', 'unit', 'pieces', 'desired_stock', 'current_stock', 'category_id', 'price'];
public $timestamps = true;
public $versioned = ['category_id', 'product_name', 'supplier','unit','desired_stock','current_stock','price','pieces', 'deleted_at'];
public function parent()
{
return $this->belongsTo('App\Category');
}
Versioning for products is working. I used the following code for it: https://github.com/ProAI/eloquent-versioning
My category model:
public function products()
{
return $this->hasMany('App\Product');
}
The code I used to check if there are products related to the category:
public function destroy($id)
{
// delete
$category = Category::withCount('products')->where('id', '=', $id)->first();
if ($category->products_count > 0) {
Session::flash('message', 'Can not delete category');
} else {
$category->delete();
// redirect
Session::flash('success', 'Category deleted');
}
return Redirect::to('categories');
}
The error message I get:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'products.category_id' in 'where clause' (SQL: select
categories
., (select count() fromproducts
inner joinproducts_version
onproducts
.id
=products_version
.ref_id
andproducts_version
.version
=products
.latest_version
wherecategories
.id
=products
.category_id
andproducts_version
.deleted_at
is null) asproducts_count
fromcategories
whereid
= 1 limit 1)
Upvotes: 2
Views: 1019
Reputation: 4168
You may need something like has many through
relationship
public function products()
{
return $this->hasManyThrough('App\Product', 'App\ProductVersion');
}
So it will link Category
to a Product
through ProductVersion
because 'category_id'
exists only in ProductVersion
Check Laravel Docs for more info
P.S. You may need to create ProductVersion
model for products_version
table
Upvotes: 1
Reputation: 47
This might work:
$category = Category::withCount('products' => function($q) {
$q->where('id', '=', $id);
})->first();
Upvotes: 0