新版本 Laravel Eloquent 关联模型 使用技巧
「这是我参与11月更文挑战的第9天,活动详情查看:2021最后一次更文挑战」
天下武功没有高下之分,只是习武之人有强弱之别。
上一篇介绍了 Laravel Eloquent 关联模型 进阶使用技巧 ,这篇介绍新版本Laravel的使用技巧,介绍一些简单优雅的新特性。
新版本使用技巧
whereHas 更简洁实现方式
在 Laravel 8.57 中发布:使用 whereRelation() 方法来简写 whereHas()。
以前
bash
User::whereHas('articles', function ($query) { $query->where('published_at', '>', now()); })->get();现在
css
User::whereRelation('articles', 'published_at', '>', now())->get();Laravel 7+ 的外键
从 Laravel 7 开始,我们不需要在迁移(migration)中为一些关系字段写两行代码: 一行写字段,一行写外键。
我们可以使用 foreignId() 方法。
Laravel 7 之前
sql
Schema::table('articles', function (Blueprint $table)) { $table->unsignedBigInteger('user_id'); $table->foreign('user_id')->references('id')->on('users'); }从 Laravel 7 开始
javascript
Schema::table('articles', function (Blueprint $table)) { $table->foreignId('user_id')->constrained(); }当我们的字段不同于表中的引用的情况,可以这么处理:
javascript
Schema::table('articles', function (Blueprint $table)) { //外键字段是 created_by_id 关联的是 users 表的 某个字段名称 $table->foreignId('created_by_id')->constrained('users', 'column_name'); }下面是通用版本技巧
两种 「whereHas」 组合使用
在 Eloquent 中,我们可以在同一条语句中使用 whereHas() 和 orDoesntHave()。
举个栗子:
scss
User::whereHas('jobs', function($query) { $query->