请教:模型关联的问题?

请问images表如何同时关联User表和Admin表?
图片资源表:images

请教:模型关联的问题

请教:模型关联的问题
这是我写的关联方式

class Image extends Model
{
    protected $fillable = [
        'auth_model', 'model_id', 'name', 'path'
    ];

    public function user()
    {
        return $this->belongsTo(User::class, 'model_id');
    }

    public function admin()
    {
        return $this->belongsTo(Admin::class, 'model_id');
    }
}
public function index(ImageRequest $request)
    {
        $images = Image::query()
            ->with(['user', 'admin'])
            ->paginate($request->page);
        return $images;
    }

得到的结果

[
            {
                "id": 1,
                "auth_model": "App\\Models\\Admin",
                "model_id": 1,
                "name": "1.png",
                "user": {
                    "id": 1,
                    "name": "Echo",
                },
                "admin": {
                    "id": 1,
                    "name": "Admin",
                }
            },
            {
                "id": 2,
                "auth_model": "App\\Models\\User",
                "model_id": 1,
                "name": "1.png",
                "user": {
                    "id": 1,
                    "name": "Echo",
                },
                "admin": {
                    "id": 1,
                    "name": "Admin",
                }
            }
]

预期的结果是下面这样,我知道我写的关联方式是只能是上面的结果,想请教大佬们如何关联可以得到我预期的结果。😂

[
            {
                "id": 1,
                "auth_model": "App\\Models\\Admin",
                "model_id": 1,
                "name": "1.png",
                "admin": {
                    "id": 1,
                    "name": "Admin",
                }
            },
            {
                "id": 2,
                "auth_model": "App\\Models\\User",
                "model_id": 1,
                "name": "1.png",
                "user": {
                    "id": 1,
                    "name": "Echo",
                }
            }
]
《L01 基础入门》
我们将带你从零开发一个项目并部署到线上,本课程教授 Web 开发中专业、实用的技能,如 Git 工作流、Laravel Mix 前端工作流等。
《L02 从零构建论坛系统》
以构建论坛项目 LaraBBS 为线索,展开对 Laravel 框架的全面学习。应用程序架构思路贴近 Laravel 框架的设计哲学。
最佳答案

模型关联《Laravel 9 中文文档》

文档的例子应该应该可以满足你的需求

1年前 评论
讨论数量: 4

模型关联《Laravel 9 中文文档》

文档的例子应该应该可以满足你的需求

1年前 评论

morphMany ,但是这样admin和user方法需要合并在一起

可以看下这个 github.com/deatil/larke-admin/blob...

1年前 评论

谢谢二位提供的帮助 @Eyeswap @deatil :+1: ,根据提供的信息,问题已完美解决的 :smile:。代码奉上,供参考

public function authMode()
{
      return $this->morphTo(__FUNCTION__, 'auth_model', 'model_id');
}
public function index(ImageRequest $request)
 {
        $images = QueryBuilder::for(Image::query())
            ->allowedIncludes(['authMode'])
            ->paginate($request->page);
        return ImageResource::collection($images);
 }
1年前 评论
s51983 1年前

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