“This is the 8th day of my participation in the Gwen Challenge in November. Check out the details: The Last Gwen Challenge in 2021”

There is no superior or inferior martial arts in the world, only those who practice martial arts are strong or weak.

1. Eloquent Usage of the Laravel Eloquent Association Model

Eloquent Relational modeling techniques

How do I modify the parent updated_AT

If we want to update a piece of data and update its parent’s updated_at field (e.g., we want to update articles. Updated_at as well), we just use $touches = [‘article’] in the child model; Properties.

class Comment extends Model
{
    protected $touches = ['article'];
}
Copy the code

Count the number of subassociated records using withCount ()

If we have hasMany() associations and we want to count the number of sub-association records, do not write a special query.

For example, if we have articles and comments on our user model, use withCount().

public function index()
{
    $users = User::withCount(['articles', 'comments'])->get();
    return view('users', compact('users'));
}
Copy the code

In the Blade file, meanwhile, we can get these numbers by using the {relationship}_count property:

@foreach ($users as $user)
<tr>
    <td>{{ $user->name }}</td>
    <td class="text-center">{{ $user->articles_count }}</td>
    <td class="text-center">{{ $user->comments_count }}</td>
</tr>
@endforeach
Copy the code

You can also sort by these statistical fields:

User::withCount('comments')->orderBy('comments_count', 'desc')->get(); 
Copy the code

Filter queries in association relationships

If we want to load relational data, we also need to specify some closure functions that restrict or sort.

For example, if we want to obtain information about the top 5 most populous countries, we can do it as follows:

$countries = Country::with(['contries' => function($query) { $query->orderBy('population', 'desc'); $query->take(5);  }])->get();Copy the code

Dynamic preloading of correlation models

Not only can we achieve real-time preloading of the association model, but we can also dynamically set certain associations according to the situation, which need to be handled in the model initialization method:

class HobbyTag extends Model { protected $with = ['hobby']; public function __construct() { parent::__construct(); $this->with = ['hobby']; if (user()->check()) { $this->with[] = 'user'; }}}Copy the code

Use hasMany instead of belongsTo

In an association relationship, the ID of the parent relationship is needed in the record that creates the child relationship

Using hasMany in this case is cleaner than belongsTo.

Such as:

If Post -> belongsTo(User), and User -> hasMany(Post)

Post::create([
    'user_id' => auth()->id(),
    'title' => request()->input('title'),
    'post_text' => request()->input('post_text'),
]);
Copy the code

It can be created like this:

auth()->user()->posts()->create([
    'title' => request()->input('title'),
    'post_text' => request()->input('post_text'),
]);
Copy the code

Customize the pivot attribute name

If we want to rename “pivot” and call the relationship in some other way, we can name the relationship in the relationship declaration using ->as(‘name’).

Model the Model:

public function podcasts() {
    return $this->belongsToMany('App\Podcast')
        ->as('subscription')
        ->withTimestamps();
}
Copy the code

Controller Controller:

$podcasts = $user->podcasts();
foreach ($podcasts as $podcast) {
    // instead of $podcast->pivot->created_at ...
    echo $podcast->subscription->created_at;
}
Copy the code

One line of code updates the attribution

If there is a belongsTo() relationship, we can update the Elquent relationship with just one statement:

// if Project -> belongsTo(User::class)
$project->user->update(['email' => '[email protected]']); 
Copy the code

Last but not least

Technical group please come here. Or add my wechat account wangzhongyang0601 to learn together.

Thank you for your support. Thank you.