嵌套预加载 MorphTo 关联的一个问题需注意
准备工作
首先我们创建三张表
posts
id - integer
name - string
users
id - integer
nickname - string
images
id - integer
url - string
imageable_id - integer
imageable_type - string
接着我们在 images
模型中增加 morphTo
的关联
public function imageable()
{
return $this->morphTo();
}
问题场景
Images::with(['imageable:id,name'])->get();
在上面使用过程中发现一个问题就是我们在设计表的时候,posts
和 users
中的字段都是不同的,那么这时候会有一个需求是在 with
中判断表的来源是 posts
还是 users
来进行查询不同的表字段已达到预期的效果
类似于 whereHasMorph
Images::whereHasMorph(
'imageable',
[Users::class, Posts::class],
function (Builder $query, $type) {
if ($type === Users::class) {
$query->selectRaw("id,nickname");
} elseif ($type === Posts::class) {
$query->selectRaw("id,name");
}
}
);
结语
目前没有找到有效的办法能够实现这一目的,仅此一个能够实现的办法如下
$imageUsers = images::with([
'imageable' => function ($query) {
$query->selectRaw("id,nickname");
}
])->where('imageable_type', 'App\Users')->get();
$imagePosts = images::with([
'imageable' => function ($query) {
$query->selectRaw("id,name");
}
])->where('imageable_type', 'App\Posts')->get();
就是通过两次分别查询,但这种方案在复杂的查询语句中则是增加了很多代码。
本作品采用《CC 协议》,转载必须注明作者和本文链接