如何在Laravel 8的Model中编写返回整数而非关联实例的方法
在Laravel 8 Model中返回整数而非关联实例的实现方案
方案1:Model内部编写独立自定义方法
不要修改原有关联方法的返回值(关联方法必须返回关联实例才能支持Laravel原生的关联查询、预加载等特性),单独新增方法返回整数即可,示例如下:
// app/Models/Post.php 示例:Post模型关联User模型,需要返回所属用户ID的整数值 namespace App\Models; use Illuminate\Database\Eloquent\Model; class Post extends Model { // 原有标准关联方法,返回关联实例 public function user() { return $this->belongsTo(User::class); } // 实现方式1:访问器方式,调用时直接取属性即可 public function getUserIdAttribute(): int { // 直接读取模型原始属性,不会触发关联加载 return (int) $this->attributes['user_id']; } // 实现方式2:普通自定义方法 public function userId(): int { return (int) $this->user_id; } }
外部调用示例:
// 访问器调用 $userId = Post::find(1)->user_id; // 普通方法调用 $userId = Post::find(1)->userId();
两种方式都直接返回整数值,不会返回User关联实例。
方案2:外部调用时直接取值(无需修改Model代码)
- 单条记录查询时用
value()方法直接取关联字段的整数值,不会加载完整关联模型:
$userId = Post::find(1)->user()->value('id');
- 列表批量查询时直接选择外键字段,或用
withCount别名获取远层关联ID,避免N+1问题:
// 直接查询外键,后续读取不需要加载关联 $posts = Post::select('*', 'user_id')->get(); foreach ($posts as $post) { $userId = $post->user_id; // 直接得到整数值 } // 获取远层关联ID示例:比如获取文章所属分类的父分类ID $posts = Post::withCount(['category.parent as parent_category_id' => function($query) { $query->select(\DB::raw('id')); }])->get(); $parentCategoryId = $posts[0]->parent_category_id; // 直接得到整数值
扩展:统计类整数值返回
如果需要返回的是统计类整数(如评论数、点赞数),可以参考以下写法:
// 在Model中新增访问器 public function getCommentCountAttribute(): int { return (int) $this->comments()->count(); }
注意:所有关联方法必须保持返回关联实例的写法,不要修改关联方法内部逻辑直接返回整数,否则会破坏Laravel关联的原生功能。
内容的提问来源于stack exchange,提问作者ayoubbouih
相关产品推荐
相关产品推荐

