Skip to content

Instantly share code, notes, and snippets.

@edwinheij
Created January 21, 2020 10:36
Show Gist options
  • Save edwinheij/e96f2d24b52d6d93fe3a2d16f05d1dbc to your computer and use it in GitHub Desktop.
Save edwinheij/e96f2d24b52d6d93fe3a2d16f05d1dbc to your computer and use it in GitHub Desktop.
Eloquent Sheet Cheat, the short one
in One to One:
u have to use HasOne on the first model and BelongsTo on the second model
to add record on the first model (HasOne) use the save function
example: $post->country()->save($country);
to add record on the second model (BelongsTo) use the associate function
example: $country->post()->associate($post)->save();
in One to Many:
u have to use HasMany on the first model and BelongsTo on the second model
to add record on the first model (HasMany) use saveMany functions
example: $post->comments()->save($comment);
example: $post->comments()->saveMany([$comment1, $comment2]);
to add record on the second model (BelongsTo) use the associate function
example: $comment->post()->associate($post)->save();
in Polymorphic One to Many:
u have to use MorphMany on the main model and MorphTo on all the (***able) models
to add records on all the other models use the MorphMany
example: $course->tags()->save($tag);
example: $course->tags()->saveMany([$tag, $tag2]);
to add record on the second model (BelongsTo) use the associate function
example: $tag->course()->associate($account)->save();
in Many to Many:
u have to use BelongsToMany on the first model and BelongsToMany on the second model
to add records on the pivot table use attach or sync functions
- both functions accepts single ID or array of ID’s
- the difference is attach checks if the record already exist on the pivot table while sync don’t
before being able to attach any data you must save the model first.
example: $user->roles()->attach([$roleId1, $roleId2]);
example: $user->roles()->sync([$roleId1, $roleId2]);
the pivot table should have the following columns:
. (***able) ID
. (***able) Type
in Polymorphic Many to Many:
u have to use MorphToMany on the main model and MorphedByMany on all the (***able) models
to add records on all the other models MorphedByMany use the save or saveMany
example: $course->tags()->save($tag);
example: $course->tags()->saveMany([$tag_1, $tag_2]);
to add record on the main model (MorphToMany) use the attach or sync function
example: $tags->courses()->attach([$tag_1, $tag_2]);
example: $tags->courses()->sync([$tag_1, $tag_2]);
the pivot table should have the following columns:
. main model ID
. (***able) ID
. (***able) Type
in Has Many Through (shortcut):
u have to use HasManyThrough on the first table and have the normal relations on the other 2 tables
this doesn’t work for ManyToMany relationships (where there’s a pivot table)
however there’s a nice and easy solution {check out another note}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment