请教模型关联

在表中有一个Approver List 表,其表结构如下:

DepApproverID ApproverID
1 1,2,3,4
2 3,5

其中ApproverID中的值分别为User表中的UserID值,请问该如果在模型中将User表的UserName关联到Department表上,显示以下效果:

DepApproverID Approver
1 测试账号1,测试账号2,测试账号3,测试账号4
2 测试账号2,测试账号5
《L03 构架 API 服务器》
你将学到如 RESTFul 设计风格、PostMan 的使用、OAuth 流程,JWT 概念及使用 和 API 开发相关的进阶知识。
《L02 从零构建论坛系统》
以构建论坛项目 LaraBBS 为线索,展开对 Laravel 框架的全面学习。应用程序架构思路贴近 Laravel 框架的设计哲学。
最佳答案

工作中也见过这样存的,虽然不能用Laravel内置的关联,但我实验了一下,可以自己实现一下。假如你的表结构是这样的(如果我没理解错的话):

Departments表:

file

Users表:

file

然后大概可以这样写Departments模型:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use App\User;

class Department extends Model
{
    public $timestamps = false;
    protected $fillable = ['approver_ids'];


    // 定义一个获取器,将逗号分隔的字段转为数组
    public function getApproverIdsAttribute($commaSeparatedIds)
    {
        return explode(',', $commaSeparatedIds);
    }

    // $department->users 获取关联关系
    // Illuminate\Database\Eloquent\Collection
    public function getUsersAttribute()
    {
        if (!$this->relationLoaded('users')) {
            $users = User::whereIn('id', $this->approver_ids)->get();

            $this->setRelation('users', $users);
        }

        return $this->getRelation('users');
    }


    // $department->users 获取查询构造器
    // Illuminate\Database\Eloquent\Builder
    public function users()
    {
        return User::whereIn('id', $this->approver_ids);
    }
}

打开tinker实验一下:

file

可以实现获取用户名。

file

但是有一些操作不能做:

file

4年前 评论
讨论数量: 6

虽然现在很少人用 , 分隔了,不过这个问题同问 :joy:

4年前 评论
半人间 4年前

这种还想用模型关联来做啊 Eloquent 已吐血

这种数据结果还不如直接写原生 SQL 呢

4年前 评论

当你选择使用逗号拼接的时候,就已经选择放弃使用数据库的外键关联操作了,只能自己写逻辑代码查询了

4年前 评论
cxxxx

id Approver DepApproverID

1 测试账号1 1

2 测试账号2 2

这样是否可以呢 :joy: ,用账号去关联 id ,你想解决的问题是不想存多条是吗? :cry:

4年前 评论

工作中也见过这样存的,虽然不能用Laravel内置的关联,但我实验了一下,可以自己实现一下。假如你的表结构是这样的(如果我没理解错的话):

Departments表:

file

Users表:

file

然后大概可以这样写Departments模型:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use App\User;

class Department extends Model
{
    public $timestamps = false;
    protected $fillable = ['approver_ids'];


    // 定义一个获取器,将逗号分隔的字段转为数组
    public function getApproverIdsAttribute($commaSeparatedIds)
    {
        return explode(',', $commaSeparatedIds);
    }

    // $department->users 获取关联关系
    // Illuminate\Database\Eloquent\Collection
    public function getUsersAttribute()
    {
        if (!$this->relationLoaded('users')) {
            $users = User::whereIn('id', $this->approver_ids)->get();

            $this->setRelation('users', $users);
        }

        return $this->getRelation('users');
    }


    // $department->users 获取查询构造器
    // Illuminate\Database\Eloquent\Builder
    public function users()
    {
        return User::whereIn('id', $this->approver_ids);
    }
}

打开tinker实验一下:

file

可以实现获取用户名。

file

但是有一些操作不能做:

file

4年前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!