Laravel save / update many to many relationship

tldr; Use sync with 2nd param false Many-to-many relationship is belongsToMany on both models: // Task model public function users() { return $this->belongsToMany(‘User’, ‘user_tasks’); // assuming user_id and task_id as fk } // User model public function tasks() { return $this->belongsToMany(‘Task’, ‘user_tasks’); } In order to add new relation use attach or sync. Difference between … Read more

HABTM Polymorphic Relationship

No, you can’t do that, there’s no such thing as a polymorphic has_and_belongs_to_many association. What you can do is create a middle model. It would probably be something like this: class Subscription < ActiveRecord::Base belongs_to :attendee, :polymorphic => true belongs_to :event end class Event < ActiveRecord::Base has_many :subscriptions end class User < ActiveRecord::Base has_many :subscriptions, … Read more

How to find all the relations between all mysql tables?

The better way, programmatically speaking, is gathering data from INFORMATION_SCHEMA.KEY_COLUMN_USAGE table as follows: SELECT `TABLE_SCHEMA`, — Foreign key schema `TABLE_NAME`, — Foreign key table `COLUMN_NAME`, — Foreign key column `REFERENCED_TABLE_SCHEMA`, — Origin key schema `REFERENCED_TABLE_NAME`, — Origin key table `REFERENCED_COLUMN_NAME` — Origin key column FROM `INFORMATION_SCHEMA`.`KEY_COLUMN_USAGE` — Will fail if user don’t have privilege WHERE … Read more

Laravel Eloquent – Attach vs Sync

attach(): Insert related models when working with many-to-many relations No array parameter is expected Example: $user = User::find(1); $user->roles()->attach(1); sync(): Similar to the attach() method, the sync() method is used to attach related models. However, the main differences are: sync() accepts an array of IDs to place on the pivot table Secondly, most important, the … Read more

Implementation difference between Aggregation and Composition in Java

Composition final class Car { private final Engine engine; Car(EngineSpecs specs) { engine = new Engine(specs); } void move() { engine.work(); } } Aggregation final class Car { private Engine engine; void setEngine(Engine engine) { this.engine = engine; } void move() { if (engine != null) engine.work(); } } In the case of composition, the … Read more