请教:模型关联的问题?

请问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",
                }
            }
]
《L05 电商实战》
从零开发一个电商项目,功能包括电商后台、商品 & SKU 管理、购物车、订单管理、支付宝支付、微信支付、订单退款流程、优惠券等
《G01 Go 实战入门》
从零开始带你一步步开发一个 Go 博客项目,让你在最短的时间内学会使用 Go 进行编码。项目结构很大程度上参考了 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年前

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