Skip to content

Laravel Eloquent 关联模型 进阶使用技巧

「这是我参与11月更文挑战的第8天,活动详情查看:2021最后一次更文挑战

天下武功没有高下之分,只是习武之人有强弱之别。

上一篇介绍了 Laravel Eloquent 关联模型使用技巧 ,这篇介绍进阶技巧。

Eloquent关联模型进阶技巧

如何修改父级 updated_at

如果我们想更新一条数据同时更新它父级关联的 updated_at 字段 (例如:我们添加一条文章评论,想同时更新文章的 articles.updated_at),只需要在子模型中使用 $touches = ['article']; 属性。

scala
class Comment extends Model {     protected $touches = ['article']; }

使用 withCount () 统计子关联记录数

如果我们有 hasMany() 的关联,并且我们想统计子关联记录的条数,不要写一个特殊的查询。

例如,如果我们的用户模型上有文章和评论,使用 withCount()

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

同时,在 Blade 文件中,我们可以通过使用 {relationship}_count 属性获得这些数量:

bash
@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

还可以按照这些统计字段进行排序:

css
User::withCount('comments')->orderBy('comments_count', 'desc')->get();

在关联关系中过滤查询