Jelmer Bouman
Jelmer Bouman

Reputation: 109

Laravel eloquent, How to define relationships with versioning

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() from products inner join products_version on products.id = products_version.ref_id and products_version.version = products.latest_version where categories.id = products.category_id and products_version.deleted_at is null) as products_count from categories where id = 1 limit 1)

Upvotes: 2

Views: 1019

Answers (2)

SergkeiM
SergkeiM

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

Ehpansei
Ehpansei

Reputation: 47

This might work:

 $category = Category::withCount('products' => function($q) {
     $q->where('id', '=', $id);
 })->first();

Upvotes: 0

Related Questions