Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does eloquent recognize tables?

I am curious about how eloquent knows in which table it should save the records we give it by running $ php artisan tinker . I do not actually remember setting so an option.

like image 932
Nico Orfi Avatar asked Dec 20 '15 18:12

Nico Orfi


People also ask

How does Laravel eloquent work?

Eloquent is an object relational mapper (ORM) that is included by default within the Laravel framework. An ORM is software that facilitates handling database records by representing data as objects, working as a layer of abstraction on top of the database engine used to store an application's data.

How do you join a table in eloquent?

If you want to join two or multiple tables in laravel then you can use laravel eloquent join(), left join(), right join(), cross join(). And another option to join two or multiple table, you can use laravel eloquent relationships instead of laravel join.

What is relationship in eloquent?

Defining Relationships. Eloquent relationships are defined as methods on your Eloquent model classes. Since relationships also serve as powerful query builders, defining relationships as methods provides powerful method chaining and querying capabilities.

What is Laravel eloquent query?

Laravel includes Eloquent, an object-relational mapper (ORM) that makes it enjoyable to interact with your database. When using Eloquent, each database table has a corresponding "Model" that is used to interact with that table.


1 Answers

In Laravel when using Eloquent you should assign a table name using the property $table for example:

protected $table = 'some_thing';

Otherwise it assumes that the table name is the plural form of the model name and in this case for User model the table name should be users. Follwing paragraph is taken from Laravel website:

Table Names

Note that we did not tell Eloquent which table to use for our Flight model. The "snake case", plural name of the class will be used as the table name unless another name is explicitly specified. So, in this case, Eloquent will assume the Flight model stores records in the flights table.

// You may use this instead:
class Flight extends Model
{
    // Explicit table name example
    protected $table = 'my_flights';
}

So, if you don't follw this convention when creating/naming your database tables that Laravel expects then you have to tell Laravel the name of the table for a model using a protected $table property in your model.

Read the documentation here.

like image 74
The Alpha Avatar answered Sep 30 '22 05:09

The Alpha