The introduction

In the previous chapter, we introduced the one-to-one in the association relation of laravel model, and introduced the operation method of association. Difficult concepts are hard to understand, let alone code, so we won’t cover difficult relationships, regardless of their efficiency.

In this installment, I will talk about two commonly used correlation models.

BelongsTo relationship

It’s like finding the opposite of a word, or finding a mirror image of an image. Where there is action, there is reaction. In the one-to-one relationship model, A has A B, and conversely, B belongs to A. This is the belongsTo relationship first.

Add a relationship to the User model in the model Profile:

class Profile extends Model {
    public function user()
    {
        return $this->belongsTo('App\User'); }}Copy the code

That is, there is a profile that is subordinate to user, which corresponds exactly to hasOne for the User model. Use this relation in code:

$email = Profile::where('id'.3)->first()->user->email;
Copy the code

The first method returns an instance of the Profile model object. In the Profile class we declare the User () method for the relational user model, so here we chain call the user property and return an App\User object instance that contains all the attributes of the User model. Therefore, the email attribute also returns the value of the field in the database.

One-to-many relationship

Another common association is one-to-many. For example, a user with multiple phone numbers, a status with multiple events, an item with multiple tags, etc., are all common uses of one-to-many.

We use the State model with multiple events to demonstrate the declaration and application of one-to-many relationships. Create a model file on the command line while creating the migration file:

php artisan make:model State --migration
Copy the code

By default, the following code is generated in the app\ state.php file:

use Illuminate\Database\Eloquent\Model;
class State extends Model {}
Copy the code

SQL > create database table migration file, manually implement migration field:

public function up()
{
    Schema::create('states'.function(Blueprint $table)
    {
        $table->increments('id');
        $table->string('name');
        $table->string('abbreviation');
        $table->timestamps();
    });
}
Copy the code

And delete tables when the migration is withdrawn:

public function down()
{
    Schema::drop('states');
}
Copy the code

Then execute the migration instruction from the command line:

php artisan migrate
Copy the code

The database table States is created successfully.

We said that associations require foreign keys, so we need to manually append a field state_id to the Events table that points to the ID field of the newly created table States. Execute command line to create migration file:

php artisan make:migration add_state_id_to_events_table --table=events
Copy the code

Manually implement the modification of the migration file:

public function up()
{
    Schema::table('events'.function (Blueprint $table) {
        $table->integer('state_id')->unsigned()->nullable();
        $table->foreign('state_id')->references('id')->on('states');
    });
}
Copy the code

And manually delete the appended fields when rolling back the migration:

public function down()
{
    Schema::table('events'.function (Blueprint $table) {
        $table->dropForeign('events_state_id_foreign');
        $table->dropColumn('state_id');
    });
}
Copy the code

With the basic data ready, add associations to the model:

class State extends Model {
    public function events() {
        return $this->hasMany('App\Event'); }}Copy the code

Pretty straightforward, one state, several events. Conversely, an event that must belong to a certain state is a belongsTo relationship.

class Event extends Model {
    public function state()
    {
        return $this->belongsTo('App\State'); }}Copy the code

The code layer is ready to be used. For example, when creating an event, specify its state manually:

$event = new Event;
$event->name = "Laravel Hacking and Pizza";
$event->state_id = 41;
$event->save();
Copy the code

Note that the hasMany association, which returns a collection of multiple models, can then chain-call all the methods of the collection.

Write in the last

This article does not fail to briefly introduce belongsTo and hasMany association relationships, which are second only to hasOne relationship in the code and used more frequently. Efficiency is simply the cost of one more SQL query based on the foreign key. However, after understanding the principle, in the operation of internal consumption of code, must not abuse association, otherwise it will seriously consume performance.

Happy coding 🙂

I am a @programmer assistant, an original author in the IT field who focuses on programming knowledge and circle dynamics