请教:模型关联的问题?
请问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",
}
}
]
模型关联《Laravel 9 中文文档》
文档的例子应该应该可以满足你的需求