多态关联查询中使用 with ,morphWith 方法,不知道如何对查找的模型分别增加字段约束

业务场景

获取 图片信息 当获取posts时 只取字段 id name ,当获取 users时 取 id name。

表结构

posts
id - integer
name - string
status - integer
users
id - integer
name - string
phone - int
age - int
status - int

images
id - integer
url - string
imageable_id - integer
imageable_type - string

多态关联

$imageInfos = images::with('imageable')->get();
  • imageable 为 images模型的多态关联方法,此时取出的post 和 user 为所有表字段,虽然with方法 有 预加载列 ,但是多态,2个模型怎么分别加载呢,或者是有什么办法去限制吗?
《L02 从零构建论坛系统》
以构建论坛项目 LaraBBS 为线索,展开对 Laravel 框架的全面学习。应用程序架构思路贴近 Laravel 框架的设计哲学。
《G01 Go 实战入门》
从零开始带你一步步开发一个 Go 博客项目,让你在最短的时间内学会使用 Go 进行编码。项目结构很大程度上参考了 Laravel。
最佳答案

@lai $imageInfos = images::with('imageable')->where('imageable_type', 'App\User')->get();

4年前 评论
讨论数量: 4

imageable_type列不是包含的父模型的类名吗?用这个字段做条件筛选吧。

4年前 评论
lai (楼主) 4年前

@lai $imageInfos = images::with('imageable')->where('imageable_type', 'App\User')->get();

4年前 评论

@qf-Z 意思是要查两次吗?

$imageUsersInfos = images::with('imageable' => function($q){
$q->select('id','phone');
})->where('imageable_type', 'App\User')->get();
$imagePostsInfos = images::with('imageable' => function($q){
$q->select('id','name');
})->where('imageable_type', 'App\Post')->get();
4年前 评论
qf-Z 4年前
lai (作者) (楼主) 4年前

我的多态关联使用预加载,指定列也不起作用,还是查询所有列呢

2年前 评论
lai (楼主) 2年前

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