PHP code example of codewiser / belongs-to-many

1. Go to this page and download the library: Download codewiser/belongs-to-many library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

codewiser / belongs-to-many example snippets


$user->organizations()->wherePivot('role', 'accountant');

User::query()
    ->where('users.role', 'superuser')
    ->whereHas('organizations', fn(Builder $builder) => $builder
        ->where('organization_user.role', 'accountant')
    );

use Illuminate\Database\Eloquent\Attributes\UseEloquentBuilder;
use Illuminate\Database\Eloquent\Model;

#[UseEloquentBuilder(UserBuilder::class)]
class User extends Model
{
    //
}

use Codewiser\Database\Eloquent\Traits\HasPivot;
use Illuminate\Database\Eloquent\Builder;

/**
 * @extends Builder<User>
 */
class UserBuilder extends Builder
{
    use HasPivot;
}

use Illuminate\Contracts\Database\Eloquent\Builder as BuilderContract;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;

Organization::query()->whereHas('users',
    // Requires Builder explicitly (default, backward compatible);
    // gets the related model's Builder.
    fn(Builder $builder) => $builder->where('organization_user.role', 'accountant')
);

Organization::query()->whereHas('users',
    // Requires BelongsToMany explicitly; gets the relation.
    fn(BelongsToMany $builder) => $builder->wherePivot('role', 'accountant')
);

Organization::query()->whereHas('users',
    // No type; gets the related model's Builder.
    fn($builder) => $builder->where('organization_user.role', 'accountant')
);

Organization::query()->whereHas('users',
    // A Builder contract; gets the relation.
    fn(BuilderContract $builder) => $builder->wherePivot('role', 'accountant')
);

Organization::query()->whereHas('users',
    // BelongsToMany is part of the union; gets the relation.
    fn(Builder|BelongsToMany $builder) => $builder->wherePivot('role', 'accountant')
);

$user->organizations()->pivot(
    fn(PivotBuilder $builder) => $builder->whereRole('accountant')
);

Organization::query()->whereHas('users',
    fn(BelongsToMany $builder) => $builder->pivot(
        fn(MyPivotBuilder $builder) => $builder->whereRole('accountant')
    )
);

$user->organizations()->wherePivot(
    fn(MyPivotBuilder $builder) => $builder->whereRole('accountant')
);

Organization::query()->whereHas('users',
    fn(BelongsToMany $builder) => $builder->wherePivot(
        fn(MyPivotBuilder $builder) => $builder->whereRole('accountant')
    )
);

User::query()->with('organizations',
    fn(BelongsToMany $relation) => $relation->wherePivot('role', 'accountant')
)->get();

$user->load(['organizations' =>
    fn(BelongsToMany $relation) => $relation->wherePivot('role', 'accountant')
]);