Ruby on rails – Reference the same model twice?

Here’s a complete answer to this issue, in case people visiting this question are new to Ruby on Rails and having a hard time putting everything together (as I was when I first looked into this). Some parts of the solution take place in your Migrations and some in your Models: Migrations class CreatePrivateMessages < … Read more

Filtering relationships in SQL Alchemy

Please read Routing Explicit Joins/Statements into Eagerly Loaded Collections. Then using contains_eager you can structure your query and get exactly what you want: authors = ( session.query(Author) .join(Author.books) .options(contains_eager(Author.books)) # tell SA that we load “all” books for Authors .filter(Book.title.like(‘%SQL%’)) ).all() Please note that you are actually tricking sqlalchemy into thinking that it has loaded … Read more

Laravel orderBy on a relationship

It is possible to extend the relation with query functions: <?php public function comments() { return $this->hasMany(‘Comment’)->orderBy(‘column’); } [edit after comment] <?php class User { public function comments() { return $this->hasMany(‘Comment’); } } class Controller { public function index() { $column = Input::get(‘orderBy’, ‘defaultColumn’); $comments = User::find(1)->comments()->orderBy($column)->get(); // use $comments in the template } } … 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

Laravel – Eloquent “Has”, “With”, “WhereHas” – What do they mean?

With with() is for eager loading. That basically means, along the main model, Laravel will preload the relationship(s) you specify. This is especially helpful if you have a collection of models and you want to load a relation for all of them. Because with eager loading you run only one additional DB query instead of … Read more

How to implement one-to-one, one-to-many and many-to-many relationships while designing tables?

One-to-one: Use a foreign key to the referenced table: student: student_id, first_name, last_name, address_id address: address_id, address, city, zipcode, student_id # you can have a # “link back” if you need You must also put a unique constraint on the foreign key column (addess.student_id) to prevent multiple rows in the child table (address) from relating … Read more

tech