You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel(ORM)中基于表关联获取带额外标识字段的数据

在Laravel ORM中给关联分类添加用户关联标识字段

嗨,我来帮你搞定这个需求~ 你需要的是获取分类数据时,额外带上一个标识,告诉我们当前指定用户是否关联了该分类对吧?这儿有几种优雅的实现方式:

第一步:先确保模型关联正确

首先得在User和Category模型中定义好多对多关联:

User模型

// app/Models/User.php
public function categories()
{
    return $this->belongsToMany(Category::class, 'user_category');
}

Category模型

// app/Models/Category.php
public function users()
{
    return $this->belongsToMany(User::class, 'user_category');
}

方法一:使用withCount自定义统计字段(推荐)

这种方式最贴合Laravel ORM的设计,不需要手动写JOIN语句,直接利用已定义的关联:

$targetUserId = 1; // 你指定的用户ID

$categories = Category::query()
    ->withCount([
        // 自定义统计字段名is_associated,只统计当前用户的关联记录
        'users as is_associated' => function ($query) use ($targetUserId) {
            $query->where('users.id', $targetUserId);
        }
    ])
    ->get();

返回的每个Category实例会多一个is_associated字段,值为1(用户已关联)或0(未关联)。如果想要布尔值更直观,可以给Category模型加个访问器:

// 在Category模型中添加
public function getIsAssociatedAttribute($value)
{
    return (bool) $value;
}

现在$category->is_associated就会返回true或false啦~

方法二:手动LEFT JOIN构造查询

如果你更习惯原生查询的思路,也可以用leftJoin结合selectRaw来实现:

$targetUserId = 1;

$categories = Category::query()
    ->leftJoin('user_category', function ($join) use ($targetUserId) {
        $join->on('categories.id', '=', 'user_category.category_id')
             ->where('user_category.user_id', '=', $targetUserId);
    })
    ->select(
        'categories.*',
        \DB::raw('CASE WHEN user_category.id IS NOT NULL THEN 1 ELSE 0 END AS is_associated')
    )
    ->get();

这个方法和第一种效果一致,只是用了原生SQL的CASE语句来判断是否存在关联记录。

效果示例

最终你会得到类似这样的数据集:

[
    {
        "id": 1,
        "name": "Egg",
        "is_associated": true
    },
    {
        "id": 2,
        "name": "Meat",
        "is_associated": false
    },
    {
        "id": 3,
        "name": "Fish",
        "is_associated": true
    }
]

内容的提问来源于stack exchange,提问作者Saswat

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 03:52:30