Home > OS >  How to get count of many to many relationship en php laravel
How to get count of many to many relationship en php laravel

Time:10-21

hello i am working with models in laravel and i have the following structure and relationships:

Model Income

public function boxes()
{
    return $this->belongsToMany(Box::class);
}

Model Box

public function incomes()
{
   return $this->belongsToMany(Income::class);
}

public function folders()
{
    return $this->hasMany(Folder::class);
}

Model Folder

public function box()
{
    return $this->belongsTo(Box::class);
}

then I can get the count of boxes like this:

$income= Income::findOrFail($id);
$income->boxes()->count();

however I can't get the number of folders in a income

$income= Income::findOrFail($id);
$income->boxes()->folders()->count();

taking into account that between income and boxes there is a many-to-many relationship, how could I achieve this?

CodePudding user response:

You can define a new relation with hasManyThrough

Model Income


public function folders()
    {
        return $this->hasManyThrough(
            Folder::class,
            Box::class,
            'income_id', // Foreign key on boxes table...
            'box_id', // Foreign key on folders table...
            'id', // Local key on income table...
            'id' // Local key on box table...
        );
    }

Then you can easily retrieve folders associated with an income

$income= Income::findOrFail($id);
$income->boxes()->folders()->count();

CodePudding user response:

I think what you need is a belongsToMany relationship:

Model income:

public function folders() {
    return $this->belongsToMany(
        Folder::class,
        'boxes', //pivot table
        'income_id', // Foreign key from boxes to incomes table...
        'folder_id', // Foreign key from boxes to folders table...
        'id', // Local key on income table...
        'id' // Local key on folders table...
    );
}

Don't forget to check how to work with pivot data as this might be something you need in the future as well.

  • Related