BelongsToMany
class BelongsToMany extends Relation (View source)
Traits
InteractsWithPivotTable |
ForwardsCalls |
Macroable |
Properties
static protected array | $macros | The registered string macros. | from Macroable |
protected Builder | $query | The Eloquent query builder instance. | from Relation |
protected Model | $parent | The parent model instance. | from Relation |
protected Model | $related | The related model instance. | from Relation |
static protected bool | $constraints | Indicates if the relation is adding constraints. | from Relation |
static array | $morphMap | An array to map class names to their morph names in database. | from Relation |
protected string | $table | The intermediate table for the relation. | |
protected string | $foreignPivotKey | The foreign key of the parent model. | |
protected string | $relatedPivotKey | The associated key of the relation. | |
protected string | $parentKey | The key name of the parent model. | |
protected string | $relatedKey | The key name of the related model. | |
protected string | $relationName | The "name" of the relationship. | |
protected array | $pivotColumns | The pivot table columns to retrieve. | |
protected array | $pivotWheres | Any pivot table restrictions for where clauses. | |
protected array | $pivotWhereIns | Any pivot table restrictions for whereIn clauses. | |
protected array | $pivotValues | The default values for the pivot columns. | |
bool | $withTimestamps | Indicates if timestamps are available on the pivot table. | |
protected string | $pivotCreatedAt | The custom pivot table column for the created_at timestamp. | |
protected string | $pivotUpdatedAt | The custom pivot table column for the updated_at timestamp. | |
protected string | $using | The class name of the custom pivot model to use for the relationship. | |
protected string | $accessor | The name of the accessor to use for the "pivot" relationship. | |
static protected int | $selfJoinCount | The count of self joins. |
Methods
mixed | forwardCallTo(mixed $object, string $method, array $parameters) Forward a method call to the given object. | from ForwardsCalls |
static void | throwBadMethodCallException(string $method) Throw a bad method call exception for the given method. | from ForwardsCalls |
static void | macro(string $name, object|callable $macro) Register a custom macro. | from Macroable |
static void | mixin(object $mixin) Mix another object into the class. | from Macroable |
static bool | hasMacro(string $name) Checks if macro is registered. | from Macroable |
static mixed | __callStatic(string $method, array $parameters) Dynamically handle calls to the class. | from Macroable |
mixed | __call(string $method, array $parameters) Dynamically handle calls to the class. | from Macroable |
void | __construct(Builder $query, Model $parent, string $table, string $foreignPivotKey, string $relatedPivotKey, string $parentKey, string $relatedKey, string $relationName = null) Create a new belongs to many relationship instance. | |
static mixed | noConstraints(Closure $callback) Run a callback with constraints disabled on the relation. | from Relation |
void | addConstraints() Set the base constraints on the relation query. | |
void | addEagerConstraints(array $models) Set the constraints for an eager load of the relation. | |
array | initRelation(array $models, string $relation) Initialize the relation on a set of models. | |
array | match(array $models, Collection $results, string $relation) Match the eagerly loaded results to their parents. | |
mixed | getResults() Get the results of the relationship. | |
Collection | getEager() Get the relationship for eager loading. | from Relation |
Collection | get(array $columns = ['*']) Execute the query as a "select" statement. | |
void | touch() Touch all of the related models for the relationship. | |
int | rawUpdate(array $attributes = []) Run a raw update against the base query. | from Relation |
Builder | getRelationExistenceCountQuery(Builder $query, Builder $parentQuery) Add the constraints for a relationship count query. | from Relation |
Builder | getRelationExistenceQuery(Builder $query, Builder $parentQuery, array|mixed $columns = ['*']) Add the constraints for a relationship query. | |
array | getKeys(array $models, string $key = null) Get all of the primary keys for an array of models. | from Relation |
Builder | getQuery() Get the underlying query for the relation. | from Relation |
Builder | getBaseQuery() Get the base query builder driving the Eloquent builder. | from Relation |
Model | getParent() Get the parent model of the relation. | from Relation |
string | getQualifiedParentKeyName() Get the fully qualified parent key name for the relation. | |
Model | getRelated() Get the related model of the relation. | from Relation |
string | createdAt() Get the name of the "created at" column. | |
string | updatedAt() Get the name of the "updated at" column. | |
string | relatedUpdatedAt() Get the name of the related model's "updated at" column. | from Relation |
static array | morphMap(array $map = null, bool $merge = true) Set or get the morph map for polymorphic relations. | from Relation |
static array|null | buildMorphMapFromModels(array $models = null) Builds a table-keyed array from model class names. | from Relation |
static string|null | getMorphedModel(string $alias) Get the model associated with a custom polymorphic type. | from Relation |
void | __clone() Force a clone of the underlying query builder when cloning. | from Relation |
array | toggle(mixed $ids, bool $touch = true) Toggles a model (or models) from the parent. | from InteractsWithPivotTable |
array | syncWithoutDetaching(Collection|Collection|array $ids) Sync the intermediate tables with a list of IDs without detaching. | from InteractsWithPivotTable |
array | sync(Collection|Collection|array $ids, bool $detaching = true) Sync the intermediate tables with a list of IDs or collection of models. | from InteractsWithPivotTable |
array | formatRecordsList(array $records) Format the sync / toggle record list so that it is keyed by ID. | from InteractsWithPivotTable |
array | attachNew(array $records, array $current, bool $touch = true) Attach all of the records that aren't in the given current records. | from InteractsWithPivotTable |
int | updateExistingPivot(mixed $id, array $attributes, bool $touch = true) Update an existing pivot record on the table. | from InteractsWithPivotTable |
void | attach(mixed $id, array $attributes = [], bool $touch = true) Attach a model to the parent. | from InteractsWithPivotTable |
array | formatAttachRecords(array $ids, array $attributes) Create an array of records to insert into the pivot table. | from InteractsWithPivotTable |
array | formatAttachRecord(int $key, mixed $value, array $attributes, bool $hasTimestamps) Create a full attachment record payload. | from InteractsWithPivotTable |
array | extractAttachIdAndAttributes(mixed $key, mixed $value, array $attributes) Get the attach record ID and extra attributes. | from InteractsWithPivotTable |
array | baseAttachRecord(int $id, bool $timed) Create a new pivot attachment record. | from InteractsWithPivotTable |
array | addTimestampsToAttachment(array $record, bool $exists = false) Set the creation and update timestamps on an attach record. | from InteractsWithPivotTable |
bool | hasPivotColumn(string $column) Determine whether the given column is defined as a pivot column. | from InteractsWithPivotTable |
int | detach(mixed $ids = null, bool $touch = true) Detach models from the relationship. | from InteractsWithPivotTable |
Pivot | newPivot(array $attributes = [], bool $exists = false) Create a new pivot model instance. | from InteractsWithPivotTable |
Pivot | newExistingPivot(array $attributes = []) Create a new existing pivot model instance. | from InteractsWithPivotTable |
Builder | newPivotStatement() Get a new plain query builder for the pivot table. | from InteractsWithPivotTable |
Builder | newPivotStatementForId(mixed $id) Get a new pivot statement for a given "other" ID. | from InteractsWithPivotTable |
Builder | newPivotQuery() Create a new query builder for the pivot table. | from InteractsWithPivotTable |
$this | withPivot(array|mixed $columns) Set the columns on the pivot table to retrieve. | from InteractsWithPivotTable |
array | parseIds(mixed $value) Get all of the IDs from the given mixed value. | from InteractsWithPivotTable |
mixed | parseId(mixed $value) Get the ID from the given mixed value. | from InteractsWithPivotTable |
array | castKeys(array $keys) Cast the given keys to integers if they are numeric and string otherwise. | from InteractsWithPivotTable |
mixed | castKey(mixed $key) Cast the given key to convert to primary key type. | from InteractsWithPivotTable |
array | castAttributes(array $attributes) Cast the given pivot attributes. | from InteractsWithPivotTable |
mixed | getTypeSwapValue(string $type, mixed $value) Converts a given value to a given type value. | from InteractsWithPivotTable |
$this | performJoin(Builder|null $query = null) Set the join clause for the relation query. | |
$this | addWhereConstraints() Set the where clause for the relation query. | |
array | buildDictionary(Collection $results) Build model dictionary keyed by the relation's foreign key. | |
string | getPivotClass() Get the class being used for pivot models. | |
$this | using(string $class) Specify the custom pivot model to use for the relationship. | |
$this | as(string $accessor) Specify the custom pivot accessor to use for the relationship. | |
$this | wherePivot(string $column, string $operator = null, mixed $value = null, string $boolean = 'and') Set a where clause for a pivot table column. | |
$this | wherePivotIn(string $column, mixed $values, string $boolean = 'and', bool $not = false) Set a "where in" clause for a pivot table column. | |
$this | orWherePivot(string $column, string $operator = null, mixed $value = null) Set an "or where" clause for a pivot table column. | |
$this | withPivotValue(string $column, mixed $value = null) Set a where clause for a pivot table column. | |
$this | orWherePivotIn(string $column, mixed $values) Set an "or where in" clause for a pivot table column. | |
Collection|Model | findOrNew(mixed $id, array $columns = ['*']) Find a related model by its primary key or return new instance of the related model. | |
Model | firstOrNew(array $attributes) Get the first related model record matching the attributes or instantiate it. | |
Model | firstOrCreate(array $attributes, array $joining = [], bool $touch = true) Get the first related record matching the attributes or create it. | |
Model | updateOrCreate(array $attributes, array $values = [], array $joining = [], bool $touch = true) Create or update a related record matching the attributes, and fill it with values. | |
Model|Collection|null | find(mixed $id, array $columns = ['*']) Find a related model by its primary key. | |
Collection | findMany(mixed $ids, array $columns = ['*']) Find multiple related models by their primary keys. | |
Model|Collection | findOrFail(mixed $id, array $columns = ['*']) Find a related model by its primary key or throw an exception. | |
mixed | first(array $columns = ['*']) Execute the query and get the first result. | |
Model|BelongsToMany | firstOrFail(array $columns = ['*']) Execute the query and get the first result or throw an exception. | |
array | shouldSelect(array $columns = ['*']) Get the select columns for the relation query. | |
array | aliasedPivotColumns() Get the pivot columns for the relation. | |
LengthAwarePaginator | paginate(int $perPage = null, array $columns = ['*'], string $pageName = 'page', int|null $page = null) Get a paginator for the "select" statement. | |
Paginator | simplePaginate(int $perPage = null, array $columns = ['*'], string $pageName = 'page', int|null $page = null) Paginate the given query into a simple paginator. | |
bool | chunk(int $count, callable $callback) Chunk the results of the query. | |
bool | each(callable $callback, int $count = 1000) Execute a callback over each item while chunking. | |
void | hydratePivotRelation(array $models) Hydrate the pivot table relationship on the models. | |
array | migratePivotAttributes(Model $model) Get the pivot attributes from a model. | |
void | touchIfTouching() If we're touching the parent model, touch. | |
bool | touchingParent() Determine if we should touch the parent on sync. | |
string | guessInverseRelation() Attempt to guess the name of the inverse of the relation. | |
Collection | allRelatedIds() Get all of the IDs for the related models. | |
Model | save(Model $model, array $pivotAttributes = [], bool $touch = true) Save a new model and attach it to the parent model. | |
array | saveMany(Collection|array $models, array $pivotAttributes = []) Save an array of new models and attach them to the parent model. | |
Model | create(array $attributes = [], array $joining = [], bool $touch = true) Create a new instance of the related model. | |
array | createMany(array $records, array $joinings = []) Create an array of new instances of the related models. | |
Builder | getRelationExistenceQueryForSelfJoin(Builder $query, Builder $parentQuery, array|mixed $columns = ['*']) Add the constraints for a relationship query on the same table. | |
string | getExistenceCompareKey() Get the key for comparing against the parent key in "has" query. | |
string | getRelationCountHash() Get a relationship join table hash. | |
$this | withTimestamps(mixed $createdAt = null, mixed $updatedAt = null) Specify that the pivot table has creation and update timestamps. | |
string | getForeignPivotKeyName() Get the foreign key for the relation. | |
string | getQualifiedForeignPivotKeyName() Get the fully qualified foreign key for the relation. | |
string | getRelatedPivotKeyName() Get the "related key" for the relation. | |
string | getQualifiedRelatedPivotKeyName() Get the fully qualified "related key" for the relation. | |
string | getTable() Get the intermediate table for the relationship. | |
string | getRelationName() Get the relationship name for the relationship. | |
string | getPivotAccessor() Get the name of the pivot accessor for this relationship. |
Details
protected mixed forwardCallTo(mixed $object, string $method, array $parameters)
Forward a method call to the given object.
static protected void throwBadMethodCallException(string $method)
Throw a bad method call exception for the given method.
static void macro(string $name, object|callable $macro)
Register a custom macro.
static void mixin(object $mixin)
Mix another object into the class.
static bool hasMacro(string $name)
Checks if macro is registered.
static mixed __callStatic(string $method, array $parameters)
Dynamically handle calls to the class.
mixed __call(string $method, array $parameters)
Dynamically handle calls to the class.
void __construct(Builder $query, Model $parent, string $table, string $foreignPivotKey, string $relatedPivotKey, string $parentKey, string $relatedKey, string $relationName = null)
Create a new belongs to many relationship instance.
static mixed noConstraints(Closure $callback)
Run a callback with constraints disabled on the relation.
void addConstraints()
Set the base constraints on the relation query.
void addEagerConstraints(array $models)
Set the constraints for an eager load of the relation.
array initRelation(array $models, string $relation)
Initialize the relation on a set of models.
array match(array $models, Collection $results, string $relation)
Match the eagerly loaded results to their parents.
mixed getResults()
Get the results of the relationship.
Collection getEager()
Get the relationship for eager loading.
Collection get(array $columns = ['*'])
Execute the query as a "select" statement.
void touch()
Touch all of the related models for the relationship.
E.g.: Touch all roles associated with this user.
int rawUpdate(array $attributes = [])
Run a raw update against the base query.
Builder getRelationExistenceCountQuery(Builder $query, Builder $parentQuery)
Add the constraints for a relationship count query.
Builder getRelationExistenceQuery(Builder $query, Builder $parentQuery, array|mixed $columns = ['*'])
Add the constraints for a relationship query.
protected array getKeys(array $models, string $key = null)
Get all of the primary keys for an array of models.
Builder getQuery()
Get the underlying query for the relation.
Builder getBaseQuery()
Get the base query builder driving the Eloquent builder.
Model getParent()
Get the parent model of the relation.
string getQualifiedParentKeyName()
Get the fully qualified parent key name for the relation.
Model getRelated()
Get the related model of the relation.
string createdAt()
Get the name of the "created at" column.
string updatedAt()
Get the name of the "updated at" column.
string relatedUpdatedAt()
Get the name of the related model's "updated at" column.
static array morphMap(array $map = null, bool $merge = true)
Set or get the morph map for polymorphic relations.
static protected array|null buildMorphMapFromModels(array $models = null)
Builds a table-keyed array from model class names.
static string|null getMorphedModel(string $alias)
Get the model associated with a custom polymorphic type.
void __clone()
Force a clone of the underlying query builder when cloning.
array toggle(mixed $ids, bool $touch = true)
Toggles a model (or models) from the parent.
Each existing model is detached, and non existing ones are attached.
array syncWithoutDetaching(Collection|Collection|array $ids)
Sync the intermediate tables with a list of IDs without detaching.
array sync(Collection|Collection|array $ids, bool $detaching = true)
Sync the intermediate tables with a list of IDs or collection of models.
protected array formatRecordsList(array $records)
Format the sync / toggle record list so that it is keyed by ID.
protected array attachNew(array $records, array $current, bool $touch = true)
Attach all of the records that aren't in the given current records.
int updateExistingPivot(mixed $id, array $attributes, bool $touch = true)
Update an existing pivot record on the table.
void attach(mixed $id, array $attributes = [], bool $touch = true)
Attach a model to the parent.
protected array formatAttachRecords(array $ids, array $attributes)
Create an array of records to insert into the pivot table.
protected array formatAttachRecord(int $key, mixed $value, array $attributes, bool $hasTimestamps)
Create a full attachment record payload.
protected array extractAttachIdAndAttributes(mixed $key, mixed $value, array $attributes)
Get the attach record ID and extra attributes.
protected array baseAttachRecord(int $id, bool $timed)
Create a new pivot attachment record.
protected array addTimestampsToAttachment(array $record, bool $exists = false)
Set the creation and update timestamps on an attach record.
protected bool hasPivotColumn(string $column)
Determine whether the given column is defined as a pivot column.
int detach(mixed $ids = null, bool $touch = true)
Detach models from the relationship.
Pivot newPivot(array $attributes = [], bool $exists = false)
Create a new pivot model instance.
Pivot newExistingPivot(array $attributes = [])
Create a new existing pivot model instance.
Builder newPivotStatement()
Get a new plain query builder for the pivot table.
Builder newPivotStatementForId(mixed $id)
Get a new pivot statement for a given "other" ID.
protected Builder newPivotQuery()
Create a new query builder for the pivot table.
$this withPivot(array|mixed $columns)
Set the columns on the pivot table to retrieve.
protected array parseIds(mixed $value)
Get all of the IDs from the given mixed value.
protected mixed parseId(mixed $value)
Get the ID from the given mixed value.
protected array castKeys(array $keys)
Cast the given keys to integers if they are numeric and string otherwise.
protected mixed castKey(mixed $key)
Cast the given key to convert to primary key type.
protected array castAttributes(array $attributes)
Cast the given pivot attributes.
protected mixed getTypeSwapValue(string $type, mixed $value)
Converts a given value to a given type value.
protected $this performJoin(Builder|null $query = null)
Set the join clause for the relation query.
protected $this addWhereConstraints()
Set the where clause for the relation query.
protected array buildDictionary(Collection $results)
Build model dictionary keyed by the relation's foreign key.
string getPivotClass()
Get the class being used for pivot models.
$this using(string $class)
Specify the custom pivot model to use for the relationship.
$this as(string $accessor)
Specify the custom pivot accessor to use for the relationship.
$this wherePivot(string $column, string $operator = null, mixed $value = null, string $boolean = 'and')
Set a where clause for a pivot table column.
$this wherePivotIn(string $column, mixed $values, string $boolean = 'and', bool $not = false)
Set a "where in" clause for a pivot table column.
$this orWherePivot(string $column, string $operator = null, mixed $value = null)
Set an "or where" clause for a pivot table column.
$this withPivotValue(string $column, mixed $value = null)
Set a where clause for a pivot table column.
In addition, new pivot records will receive this value.
$this orWherePivotIn(string $column, mixed $values)
Set an "or where in" clause for a pivot table column.
Collection|Model findOrNew(mixed $id, array $columns = ['*'])
Find a related model by its primary key or return new instance of the related model.
Model firstOrNew(array $attributes)
Get the first related model record matching the attributes or instantiate it.
Model firstOrCreate(array $attributes, array $joining = [], bool $touch = true)
Get the first related record matching the attributes or create it.
Model updateOrCreate(array $attributes, array $values = [], array $joining = [], bool $touch = true)
Create or update a related record matching the attributes, and fill it with values.
Model|Collection|null find(mixed $id, array $columns = ['*'])
Find a related model by its primary key.
Collection findMany(mixed $ids, array $columns = ['*'])
Find multiple related models by their primary keys.
Model|Collection findOrFail(mixed $id, array $columns = ['*'])
Find a related model by its primary key or throw an exception.
mixed first(array $columns = ['*'])
Execute the query and get the first result.
Model|BelongsToMany firstOrFail(array $columns = ['*'])
Execute the query and get the first result or throw an exception.
protected array shouldSelect(array $columns = ['*'])
Get the select columns for the relation query.
protected array aliasedPivotColumns()
Get the pivot columns for the relation.
"pivot_" is prefixed ot each column for easy removal later.
LengthAwarePaginator paginate(int $perPage = null, array $columns = ['*'], string $pageName = 'page', int|null $page = null)
Get a paginator for the "select" statement.
Paginator simplePaginate(int $perPage = null, array $columns = ['*'], string $pageName = 'page', int|null $page = null)
Paginate the given query into a simple paginator.
bool chunk(int $count, callable $callback)
Chunk the results of the query.
bool each(callable $callback, int $count = 1000)
Execute a callback over each item while chunking.
protected void hydratePivotRelation(array $models)
Hydrate the pivot table relationship on the models.
protected array migratePivotAttributes(Model $model)
Get the pivot attributes from a model.
void touchIfTouching()
If we're touching the parent model, touch.
protected bool touchingParent()
Determine if we should touch the parent on sync.
protected string guessInverseRelation()
Attempt to guess the name of the inverse of the relation.
Collection allRelatedIds()
Get all of the IDs for the related models.
Model save(Model $model, array $pivotAttributes = [], bool $touch = true)
Save a new model and attach it to the parent model.
array saveMany(Collection|array $models, array $pivotAttributes = [])
Save an array of new models and attach them to the parent model.
Model create(array $attributes = [], array $joining = [], bool $touch = true)
Create a new instance of the related model.
array createMany(array $records, array $joinings = [])
Create an array of new instances of the related models.
Builder getRelationExistenceQueryForSelfJoin(Builder $query, Builder $parentQuery, array|mixed $columns = ['*'])
Add the constraints for a relationship query on the same table.
string getExistenceCompareKey()
Get the key for comparing against the parent key in "has" query.
string getRelationCountHash()
Get a relationship join table hash.
$this withTimestamps(mixed $createdAt = null, mixed $updatedAt = null)
Specify that the pivot table has creation and update timestamps.
string getForeignPivotKeyName()
Get the foreign key for the relation.
string getQualifiedForeignPivotKeyName()
Get the fully qualified foreign key for the relation.
string getRelatedPivotKeyName()
Get the "related key" for the relation.
string getQualifiedRelatedPivotKeyName()
Get the fully qualified "related key" for the relation.
string getTable()
Get the intermediate table for the relationship.
string getRelationName()
Get the relationship name for the relationship.
string getPivotAccessor()
Get the name of the pivot accessor for this relationship.
© Taylor Otwell
Licensed under the MIT License.
Laravel is a trademark of Taylor Otwell.
https://laravel.com/api/5.7/Illuminate/Database/Eloquent/Relations/BelongsToMany.html