diff --git a/eloquent.md b/eloquent.md index ccdae59..0256a3f 100644 --- a/eloquent.md +++ b/eloquent.md @@ -1,34 +1,34 @@ # Eloquent ORM -- [Introduction](#introduction) -- [Basic Usage](#basic-usage) -- [Mass Assignment](#mass-assignment) -- [Insert, Update, Delete](#insert-update-delete) -- [Soft Deleting](#soft-deleting) -- [Timestamps](#timestamps) -- [Query Scopes](#query-scopes) -- [Relationships](#relationships) -- [Querying Relations](#querying-relations) -- [Eager Loading](#eager-loading) -- [Inserting Related Models](#inserting-related-models) -- [Touching Parent Timestamps](#touching-parent-timestamps) -- [Working With Pivot Tables](#working-with-pivot-tables) -- [Collections](#collections) -- [Accessors & Mutators](#accessors-and-mutators) -- [Date Mutators](#date-mutators) -- [Model Events](#model-events) -- [Model Observers](#model-observers) -- [Converting To Arrays / JSON](#converting-to-arrays-or-json) +- [Introducción](#introduction) +- [Uso básico](#basic-usage) +- [Asignación en masa](#mass-assignment) +- [Insertar, Actualizar, Eliminar](#insert-update-delete) +- [Eliminación blanda](#soft-deleting) +- [Marcas de tiempo](#timestamps) +- [Consultas con alcance](#query-scopes) +- [Relaciones](#relationships) +- [Consultas sobre relaciones](#querying-relations) +- [Carga impaciente](#eager-loading) +- [Insertando modelos relacionados](#inserting-related-models) +- [Actualizando marcas de tiempo de relaciones padre](#touching-parent-timestamps) +- [Trabajando con tablas intermedias](#working-with-pivot-tables) +- [Colecciones](#collections) +- [Descriptores de acceso y Mutadores](#accessors-and-mutators) +- [Mutadores de fecha](#date-mutators) +- [Eventos de modelos](#model-events) +- [Observadores de modelos](#model-observers) +- [Convirtiendo a Arreglos / JSON](#converting-to-arrays-or-json) -## Introduction +## Introducción The Eloquent ORM included with Laravel provides a beautiful, simple ActiveRecord implementation for working with your database. Each database table has a corresponding "Model" which is used to interact with that table. Before getting started, be sure to configure a database connection in `app/config/database.php`. -## Basic Usage +## Uso básico To get started, create an Eloquent model. Models typically live in the `app/models` directory, but you are free to place them anywhere that can be auto-loaded according to your `composer.json` file. @@ -117,7 +117,7 @@ You may also specify which database connection should be used when running an El $user = User::on('connection-name')->find(1); -## Mass Assignment +## Asignación en masa When creating a new model, you pass an array of attributes to the model constructor. These attributes are then assigned to the model via mass-assignment. This is convenient; however, can be a **serious** security concern when blindly passing user input into a model. If user input is blindly passed into a model, the user is free to modify **any** and **all** of the model's attributes. For this reason, all Eloquent models protect against mass-assignment by default. @@ -152,7 +152,7 @@ In the example above, the `id` and `password` attributes may **not** be mass ass protected $guarded = array('*'); -## Insert, Update, Delete +## Insertar, Actualizar, Eliminar To create a new record in the database from a model, simply create a new model instance and call the `save` method. @@ -240,7 +240,7 @@ If you wish to simply update the timestamps on a model, you may use the `touch` $user->touch(); -## Soft Deleting +## Eliminación blanda When soft deleting a model, it is not actually removed from your database. Instead, a `deleted_at` timestamp is set on the record. To enable soft deletes for a model, specify the `softDelete` property on the model: @@ -296,7 +296,7 @@ To determine if a given model instance has been soft deleted, you may use the `t } -## Timestamps +## Marcas de tiempo By default, Eloquent will maintain the `created_at` and `updated_at` columns on your database table automatically. Simply add these `timestamp` columns to your table and Eloquent will take care of the rest. If you do not wish for Eloquent to maintain these columns, add the following property to your model: @@ -324,7 +324,7 @@ If you wish to customize the format of your timestamps, you may override the `ge } -## Query Scopes +## Consultas con alcance Scopes allow you to easily re-use query logic in your models. To define a scope, simply prefix a model method with `scope`: @@ -366,7 +366,7 @@ Then pass the parameter into the scope call: $users = User::ofType('member')->get(); -## Relationships +## Relaciones Of course, your database tables are probably related to one another. For example, a blog post may have many comments, or an order could be related to the user who placed it. Eloquent makes managing and working with these relationships easy. Laravel supports many types of relationships: @@ -690,7 +690,7 @@ The `Tag` model may define a method for each of its relationships: } -## Querying Relations +## Consultas sobre relaciones When accessing the records for a model, you may wish to limit your results based on the existence of a relationship. For example, you wish to pull all blog posts that have at least one comment. To do so, you may use the `has` method: @@ -737,7 +737,7 @@ It may be shortened to simply: > **Note:** Relationships that return many results will return an instance of the `Illuminate\Database\Eloquent\Collection` class. -## Eager Loading +## Carga impaciente Eager loading exists to alleviate the N + 1 query problem. For example, consider a `Book` model that is related to `Author`. The relationship is defined like so: @@ -813,7 +813,7 @@ It is also possible to eagerly load related models directly from an already exis $books->load('author', 'publisher'); -## Inserting Related Models +## Insertando modelos relacionados You will often need to insert new related models. For example, you may wish to insert a new comment for a post. Instead of manually setting the `post_id` foreign key on the model, you may insert the new comment from its parent `Post` model directly: @@ -878,7 +878,7 @@ In this example, the new `Role` model will be saved and attached to the user mod User::find(1)->roles()->save($role, array('expires' => $expires)); -## Touching Parent Timestamps +## Actualizando marcas de tiempo de relaciones padre When a model `belongsTo` another model, such as a `Comment` which belongs to a `Post`, it is often helpful to update the parent's timestamp when the child model is updated. For example, when a `Comment` model is updated, you may want to automatically touch the `updated_at` timestamp of the owning `Post`. Eloquent makes it easy. Just add a `touches` property containing the names of the relationships to the child model: @@ -902,7 +902,7 @@ Now, when you update a `Comment`, the owning `Post` will have its `updated_at` c $comment->save(); -## Working With Pivot Tables +## Trabajando con tablas intermedias As you have already learned, working with many-to-many relations requires the presence of an intermediate table. Eloquent provides some very helpful ways of interacting with this table. For example, let's assume our `User` object has many `Role` objects that it is related to. After accessing this relationship, we may access the `pivot` table on the models: @@ -943,7 +943,7 @@ Laravel also allows you to define a custom Pivot model. To define a custom model } -## Collections +## Colecciones All multi-result sets returned by Eloquent, either via the `get` method or a `relationship`, will return a collection object. This object implements the `IteratorAggregate` PHP interface so it can be iterated over like an array. However, this object also has a variety of other helpful methods for working with result sets. @@ -1022,7 +1022,7 @@ Sometimes, you may wish to return a custom Collection object with your own added } -## Accessors & Mutators +## Descriptores de acceso y Mutadores Eloquent provides a convenient way to transform your model attributes when getting or setting them. Simply define a `getFooAttribute` method on your model to declare an accessor. Keep in mind that the methods should follow camel-casing, even though your database columns are snake-case: @@ -1053,7 +1053,7 @@ Mutators are declared in a similar fashion: } -## Date Mutators +## Mutadores de fecha By default, Eloquent will convert the `created_at`, `updated_at`, and `deleted_at` columns to instances of [Carbon](https://github.com/briannesbitt/Carbon), which provides an assortment of helpful methods, and extends the native PHP `DateTime` class. @@ -1074,7 +1074,7 @@ To totally disable date mutations, simply return an empty array from the `getDat } -## Model Events +## Eventos de modelos Eloquent models fire several events, allowing you to hook into various points in the model's lifecycle using the following methods: `creating`, `created`, `updating`, `updated`, `saving`, `saved`, `deleting`, `deleted`, `restoring`, `restored`. @@ -1105,7 +1105,7 @@ Eloquent models also contain a static `boot` method, which may provide a conveni } -## Model Observers +## Observadores de modelos To consolidate the handling of model events, you may register a model observer. An observer class may have methods that correspond to the various model events. For example, `creating`, `updating`, `saving` methods may be on an observer, in addition to any other model event name. @@ -1130,7 +1130,7 @@ You may register an observer instance using the `observe` method: User::observe(new UserObserver); -## Converting To Arrays / JSON +## Convirtiendo a Arreglos / JSON When building JSON APIs, you may often need to convert your models and relationships to arrays or JSON. So, Eloquent includes methods for doing so. To convert a model and its loaded relationship to an array, you may use the `toArray` method: diff --git a/queries.md b/queries.md index db221f1..31916b6 100644 --- a/queries.md +++ b/queries.md @@ -1,29 +1,29 @@ -# Query Builder +# Constructor de consultas -- [Introduction](#introduction) +- [Introducción](#introduction) - [Selects](#selects) - [Joins](#joins) -- [Advanced Wheres](#advanced-wheres) +- [Wheres avanzados](#advanced-wheres) - [Aggregates](#aggregates) -- [Raw Expressions](#raw-expressions) +- [Expresiones planas](#raw-expressions) - [Inserts](#inserts) - [Updates](#updates) - [Deletes](#deletes) - [Unions](#unions) -- [Pessimistic Locking](#pessimistic-locking) -- [Caching Queries](#caching-queries) +- [Bloqueo pesimista](#pessimistic-locking) +- [Cache de consultas](#caching-queries) -## Introduction +## Introducción -The database query builder provides a convenient, fluent interface to creating and running database queries. It can be used to perform most database operations in your application, and works on all supported database systems. +El constructor de consulta de base de datos ofrece una cómoda, conveniente y fluída forma para crear y ejecutar consultas de base de datos. Puede ser usado para ejecutar la mayoría de las operaciones con la base de datos en tu aplicación, y funciona en todos los motores de base de datos soportados. -> **Note:** The Laravel query builder uses PDO parameter binding throughout to protect your application against SQL injection attacks. There is no need to clean strings being passed as bindings. +> **Nota:** El constructor de consultas de Laravel usa vinculación de parámetros PDO en todas las consultas para proteger tu aplicación de ataques de inyección de SQL. No hay necesidad de limpiar las cadenas de texto que son pasadas como vínculos. ## Selects -#### Retrieving All Rows From A Table +#### Obtener todas las filas de una tabla $users = DB::table('users')->get(); @@ -32,25 +32,25 @@ The database query builder provides a convenient, fluent interface to creating a var_dump($user->name); } -#### Retrieving A Single Row From A Table +#### Obtener una sola fila de una tabla $user = DB::table('users')->where('name', 'John')->first(); var_dump($user->name); -#### Retrieving A Single Column From A Row +#### Obtener una sola columna de una fila $name = DB::table('users')->where('name', 'John')->pluck('name'); -#### Retrieving A List Of Column Values +#### Obtener una lista de valores de una columna $roles = DB::table('roles')->lists('title'); -This method will return an array of role titles. You may also specify a custom key column for the returned array: +Éste método retornará una rreglo de títulos de roles. Puedes también especificar un índice de una columna personalizada para el arreglo retornado: $roles = DB::table('roles')->lists('title', 'name'); -#### Specifying A Select Clause +#### Especificar una sentencia Select $users = DB::table('users')->select('name', 'email')->get(); @@ -58,34 +58,34 @@ This method will return an array of role titles. You may also specify a custom k $users = DB::table('users')->select('name as user_name')->get(); -#### Adding A Select Clause To An Existing Query +#### Agregar una sentencia Select a una consulta previa $query = DB::table('users')->select('name'); $users = $query->addSelect('age')->get(); -#### Using Where Operators +#### Usar operadores Where $users = DB::table('users')->where('votes', '>', 100)->get(); -#### Or Statements +#### O sentencias $users = DB::table('users') ->where('votes', '>', 100) ->orWhere('name', 'John') ->get(); -#### Using Where Between +#### Usar Where entre $users = DB::table('users') ->whereBetween('votes', array(1, 100))->get(); -#### Using Where Not Between +#### Usar Where no entre $users = DB::table('users') ->whereNotBetween('votes', array(1, 100))->get(); -#### Using Where In With An Array +#### Usar Where In en un array $users = DB::table('users') ->whereIn('id', array(1, 2, 3))->get(); @@ -93,12 +93,12 @@ This method will return an array of role titles. You may also specify a custom k $users = DB::table('users') ->whereNotIn('id', array(1, 2, 3))->get(); -#### Using Where Null To Find Records With Unset Values +#### Usar Where Null para encontrar registros con valores no definidos $users = DB::table('users') ->whereNull('updated_at')->get(); -#### Order By, Group By, And Having +#### Usar Order By, Group By, And Having $users = DB::table('users') ->orderBy('name', 'desc') @@ -106,16 +106,16 @@ This method will return an array of role titles. You may also specify a custom k ->having('count', '>', 100) ->get(); -#### Offset & Limit +#### Usar Offset y Limit $users = DB::table('users')->skip(10)->take(5)->get(); -## Joins +## Uniones -The query builder may also be used to write join statements. Take a look at the following examples: +El constructor de consultras puede además ser usado para escribir sentencias JOIN. Mira los siguientes ejemplos: -#### Basic Join Statement +#### Sentencia básica de Join DB::table('users') ->join('contacts', 'users.id', '=', 'contacts.user_id') @@ -123,13 +123,13 @@ The query builder may also be used to write join statements. Take a look at the ->select('users.id', 'contacts.phone', 'orders.price') ->get(); -#### Left Join Statement +#### Sentencia Left Join DB::table('users') ->leftJoin('posts', 'users.id', '=', 'posts.user_id') ->get(); -You may also specify more advanced join clauses: +Puedes también crear sentencias JOIN más avanzadas: DB::table('users') ->join('contacts', function($join) @@ -138,7 +138,7 @@ You may also specify more advanced join clauses: }) ->get(); -If you would like to use a "where" style clause on your joins, you may use the `where` and `orWhere` methods on a join. Instead of comparing two columns, these methods will compare the column against a value: +Si deseas usar una sentencia estilo "where" en tus sentencias JOIN, puedes usar el método `where` y `orWhere` en el método `join`. En vez de comparar dos columnas, estos métodos compararán la columna contra un valor: DB::table('users') ->join('contacts', function($join) @@ -149,11 +149,11 @@ If you would like to use a "where" style clause on your joins, you may use the ` ->get(); -## Advanced Wheres +## Wheres Avanzados -Sometimes you may need to create more advanced where clauses such as "where exists" or nested parameter groupings. The Laravel query builder can handle these as well: +Algunas veces puedes necesitar la ccreación de sentencias where más avanzadas como "where exists" o agrupar jerarquicamente parámetros. El constructor de consultas de Laravel pueden manejar esto también: -#### Parameter Grouping +#### Agrupación de parámetros DB::table('users') ->where('name', '=', 'John') @@ -164,11 +164,11 @@ Sometimes you may need to create more advanced where clauses such as "where exis }) ->get(); -The query above will produce the following SQL: +La consulta anterior generará la siguiente consulta SQL: select * from users where name = 'John' or (votes > 100 and title <> 'Admin') -#### Exists Statements +#### Sentencias Exists DB::table('users') ->whereExists(function($query) @@ -179,7 +179,7 @@ The query above will produce the following SQL: }) ->get(); -The query above will produce the following SQL: +La consulta anterior generará la siguiente consulta SQL: select * from users where exists ( @@ -189,9 +189,9 @@ The query above will produce the following SQL: ## Aggregates -The query builder also provides a variety of aggregate methods, such as `count`, `max`, `min`, `avg`, and `sum`. +En constructor de consultas además ofrece una variedad de métodos de agregación, como `count`, `max`, `min`, `avg` y `sum`. -#### Using Aggregate Methods +#### Usando los métodos $users = DB::table('users')->count(); @@ -204,11 +204,11 @@ The query builder also provides a variety of aggregate methods, such as `count`, $total = DB::table('users')->sum('votes'); -## Raw Expressions +## Expresiones planas -Sometimes you may need to use a raw expression in a query. These expressions will be injected into the query as strings, so be careful not to create any SQL injection points! To create a raw expression, you may use the `DB::raw` method: +Algunas veces puedes necesitar el uso de expresiones planas en una consulta. Dichas expresiones serán inyectadas dentro de la consulta como cadenas de texto, así que ten cuidado de no crear algún punto débil para inyecciones SQL! Para crear una expresión plana, puedes usar el método `DB::raw`: -#### Using A Raw Expression +#### Usar una expresión plana $users = DB::table('users') ->select(DB::raw('count(*) as user_count, status')) @@ -216,7 +216,7 @@ Sometimes you may need to use a raw expression in a query. These expressions wil ->groupBy('status') ->get(); -#### Incrementing or decrementing a value of a column +#### Aumentar o disminuir el valor de una columna: DB::table('users')->increment('votes'); @@ -233,23 +233,23 @@ You may also specify additional columns to update: ## Inserts -#### Inserting Records Into A Table +#### Insertando filas en una tabla DB::table('users')->insert( array('email' => 'john@example.com', 'votes' => 0) ); -If the table has an auto-incrementing id, use `insertGetId` to insert a record and retrieve the id: +Si las tablas tienen un ID autoincrementable, usa el método `insertGetId` para insertar una fila y retornar el ID: -#### Inserting Records Into A Table With An Auto-Incrementing ID +#### Insertar filas en una tabla con un ID autoincrementable $id = DB::table('users')->insertGetId( array('email' => 'john@example.com', 'votes' => 0) ); -> **Note:** When using PostgreSQL the insertGetId method expects the auto-incrementing column to be named "id". +> **Nota:** Cuando estés usando PostgreSQL el método `insertGetId` espera que la columna autoincrementable se llame "id". -#### Inserting Multiple Records Into A Table +#### Insertar múltiples filas en una tabla DB::table('users')->insert(array( array('email' => 'taylor@example.com', 'votes' => 0), @@ -259,7 +259,7 @@ If the table has an auto-incrementing id, use `insertGetId` to insert a record a ## Updates -#### Updating Records In A Table +#### Actualizar filas en una tabla DB::table('users') ->where('id', 1) @@ -268,55 +268,55 @@ If the table has an auto-incrementing id, use `insertGetId` to insert a record a ## Deletes -#### Deleting Records In A Table +#### Eliminar filas en una tabla DB::table('users')->where('votes', '<', 100)->delete(); -#### Deleting All Records From A Table +#### Eliminar todas las filas de una tabla DB::table('users')->delete(); -#### Truncating A Table +#### Truncar una tabla DB::table('users')->truncate(); ## Unions -The query builder also provides a quick way to "union" two queries together: +El constructor de consultas también ofrece una forma rápida para "unir" dos consultas en una sola: -#### Performing A Query Union +#### Realizar la unión de dos consultas $first = DB::table('users')->whereNull('first_name'); $users = DB::table('users')->whereNull('last_name')->union($first)->get(); -The `unionAll` method is also available, and has the same method signature as `union`. +El método `unionAll` está también disponible, y tiene la misma síntaxis que `union`. -## Pessimistic Locking +## Bloqueo pesimista -The query builder includes a few functions to help you do "pessimistic locking" on your SELECT statements. +El constructor de consultas incluye algunas funciones que te ayudan a realizar "bloqueos pesimistas" en tus sentencias SELECT. -To run the SELECT statement with a "shared lock", you may use the `sharedLock` method on a query: +Para ejecutar una sentencia SELECT con un "bloqueo compartido", puedes usar el método `sharedLock` en la consulta: DB::table('users')->where('votes', '>', 100)->sharedLock()->get(); -To "lock for update" on a SELECT statement, you may use the `lockForUpdate` method on a query: +Para "bloquear para actualizaciones" en una sentencia SELECT, puedes usar el método `lockForUpdate` en la consulta: DB::table('users')->where('votes', '>', 100)->lockForUpdate()->get(); -## Caching Queries +## Cache de consultas -You may easily cache the results of a query using the `remember` method: +Puedes fácilmente tener un cache de los resultados de una consulta con el método `remember`: -#### Caching A Query Result +#### Crear un cache de los resultados de una consulta: $users = DB::table('users')->remember(10)->get(); -In this example, the results of the query will be cached for ten minutes. While the results are cached, the query will not be run against the database, and the results will be loaded from the default cache driver specified for your application. +En este ejemplo, los resultados de la consulta serán guardados en cache durante diez minutos. Mientras los resultados estén guardados en cache, la consulta no se ejecutará otra vez en la base de datos, y los resultados será cargados del cache predeterminado configurado en tu aplicación. -If you are using a [supported cache driver](/docs/cache#cache-tags), you can also add tags to the caches: +Si estás usando un [controlador de cache soportado](/docs/cache#cache-tags), puedes además agregar etiquetas al caché: $users = DB::table('users')->cacheTags(array('people', 'authors'))->remember(10)->get(); diff --git a/references.md b/references.md index e1588d7..0a1da2a 100644 --- a/references.md +++ b/references.md @@ -7,4 +7,5 @@ Acá se dará una explicación extensa y clara sobre algunas palabras o concepto - Clausura (Función anónima) - Callback (retrollamadas) - Namespaces (espacio de nombres) -- REST (Técnica de Arquitectura de software) \ No newline at end of file +- REST (Técnica de Arquitectura de software) +- ORM (Mapeo Objeto-Relacional) \ No newline at end of file