jeudi 23 janvier 2020

Comparing withCount from nested relation belongToMany Laravel

I have 3 tables: Brands, Branches, Items The relationship are Brand hasMany Branches Items belongToMany Branches

An item can be at multiple branches and the other way around. Since there will be new branch data. I need to keep checking branch_item pivot table.

So I need to display items if there are any missing items on new branches.

Items model

class Item extends Model
{
    public function branches()
    {
        return $this->belongsToMany('App\Branch', 'branch_item', 'item_id', 'branch_id');
    }
}

My query so far

$itemsq = Item::with('brand.branches_count')->withCount('branches');
$itemsq->having('branches_count', '<=', DB::raw('brand.branches_count'));
$items = $itemsq->paginate(10);

The error

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'branches' in 'having clause'

I cant use

withCount('brand.branches_count')

I need to display list of items only if there are missing pivot data on them related to Branches total table. Example: If there are 10 total branches, and pivot table branch_item only contains 6 data. Any idea how to achive this ?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire