You don't have access to this class

Keep learning! Join and start boosting your career

Aprovecha el precio especial y haz tu profesi贸n a prueba de IA

Antes: $249

Currency
$209
Suscr铆bete

Termina en:

1 D铆as
17 Hrs
11 Min
39 Seg

Relational data: hasOne()

14/35
Resources

How to manage relationships in Yii with ActiveRecord?

In the world of web development, managing relationships between entities in a database is crucial. One of the most robust PHP frameworks, Yii, makes this possible in an extremely simple and efficient way by implementing ActiveRecord. In this guide, we'll explore how to manage relationships between entities using ActiveRecord in Yii.

What is ActiveRecord?

ActiveRecord is a design pattern that allows access to data in a database through objects. In Yii, each table in the database is associated with a class, and each row in that table is represented as an object of that class. This makes it easier to manipulate data, as you work directly with objects instead of abstract SQL queries.

How to define a relationship in ActiveRecord?

To define relationships between models in Yii, we use two magic methods: hasOne and hasMany. These functions allow you to specify how models are connected to each other by foreign keys or other criteria.

Practical example with hasOne

Let's see how to define a relationship in which a book has a single author:

public function getAuthor(){ return $this->hasOne(Author::class, ['authorId' => 'authorId']);}

Here, we are specifying that a book belongs to an author, indicating that the authorId of the author must match the authorId of the book. Just like that, a one-to-one relationship is established.

How to execute actions with this relationship?

Once the relationship is established, we can easily retrieve related data without the need to write complex queries. Let's consider the implementation of a function to get details of a book and its author:

Function to get book and author.

public function actionBook($bookId){ $book = Book::findOne($bookId);    
 if (empty($book)) { return 'Book does not exist'; }    
 printf("%s, by %s", $book->toString(), $book->getAuthor()->name);}

In this code, we search for a book by its bookId. If the book exists, we print its information and that of the associated author. The getAuthor() function returns an Author object, from which we can get attributes such as name.

Why choose Yii to manage databases?

Yii stands out in database management because of its ability to simplify common operations. Through ActiveRecord, the need to manually write complicated SQL queries such as joins is minimized, which significantly reduces development time and the possibility of errors.

By implementing relationships such as hasOne, Yii allows us to focus on business logic without worrying about the complexity of the underlying databases. This, coupled with its efficient performance and active community, makes it an ideal choice for developers looking for efficiency.

We call on all those curious and passionate about web development to continue exploring the possibilities that Yii has to offer. The ease of use and power of its tools will transform the way you interact with databases, taking your projects to the next level.

Contributions 3

Questions 0

Sort by:

Want to see more contributions, questions and answers from the community?

```js // Comparto por aqui una forma de organiacion del modelo, porque en la medida que se pone 'gordo'(muchos metodos) puede salirce de control. class Book extends ActiveRecord { /* 聽 聽 |---------------------------------------------------------------------------------- 聽 聽 | GLOBAL VARIABLES 聽 聽 |---------------------------------------------------------------------------------- 聽 聽 */ // public $title; // public $author; public static function tableName() { return 'books'; } public function getId() { // Este es por defecto el Id de las tablas return $this->id; } /* 聽 聽 |---------------------------------------------------------------------------------- 聽 聽 | FUNCTIONS 聽 聽 |---------------------------------------------------------------------------------- 聽 聽 */ // public function toString() // { // return sprintf("(%d) %s", $this->id, strtoupper($this->title)); // } /** * Funcion modificada para traer al author mediante la relacion * @return string */ public function toString() { return sprintf( "(%d) %s - %s", $this->id, $this->title, $this->getAuthor()->name ); } /* 聽 聽 |---------------------------------------------------------------------------------- 聽 聽 | RELATIONS 聽 聽 |---------------------------------------------------------------------------------- 聽 聽 */ public function getAuthor() { return $this ->hasOne(Author::class, ['id' => 'author_id']) // esta es la relacion author.id / book.author_id ->one(); } } ```
Modifique la funcion toString en Book.php: ![](https://static.platzi.com/media/user_upload/image-692442cd-14c2-4b6b-828a-13f6369e4a69.jpg) El resultado es este: ![](https://static.platzi.com/media/user_upload/image-104eb4b3-c119-4908-bb83-852ec19607c9.jpg)
Que modo tan peculiar de escribir un comentario jajajajaja ![](https://static.platzi.com/media/user_upload/image-1f178b33-d0e1-4787-8551-244541388e1c.jpg)