php - 在查询 1 中使用查询 2 来获取一个查询中的所有数据
问题描述
我有 3 张桌子:
*hinteractions (id, name...) *effects (id, name...) *hinteractions_has_effects (hinteractons_id, effects_id)
我可能在一个中间动作中有一对多的效果,而一个中间动作可能有一对多的效果,这就是我有这个连接表的原因。
我有这个雄辩的查询:
查询 1:
$informations_plante = DB::table('herbs')
->select('herbs.name as hname', 'herbs.sciname', 'herbs.id as herbid','hinteractions.id as hinteractionid','hinteractions.note as hinteractionnote','hinteractions.force_id','targets.name as targetname', 'forces.name as force_name')
->leftJoin('hinteractions', 'herbs.id', '=', 'herb_id')
->leftJoin('forces', 'forces.id', '=', 'force_id')
->leftJoin('targets', 'targets.id', '=', 'hinteractions.target_id')->where('herbs.id', $id)
//I would like to use the query 2 here to select effects.name with hinteraction.id used in this query to get effects' name in this query (I might have one to many).
->get();
查询 2:
$hinteractions_has_effects = DB::table('hinteraction_has_effects')
->select(DB::raw('effect_id, hinteraction_id','effects.name'))
->where('hinteraction_has_effects', '=', hinteraction.id (from the query 1))
->get();
使用查询 1,我检索了一些信息,例如 hinteractions_id。
我想使用这些hinteractions_id 并在查询2中使用它们。
最好的方法是合并两个查询(1 和 2)以获得一个 Eloquent 查询。
你有什么主意吗 ?
解决方案
试试下面的查询,让我知道这是否是你要找的 -
$informations_plante = DB::table('herbs')
->select('herbs.name as hname', 'herbs.sciname', 'herbs.id as herbid','hinteractions.id as hinteractionid','hinteractions.note as hinteractionnote','hinteractions.force_id','targets.name as targetname', 'forces.name as force_name', 'effects.id as effects_id', 'effects.name as effects_name')
->leftJoin('hinteractions', 'herbs.id', '=', 'herb_id')
->leftJoin('forces', 'forces.id', '=', 'force_id')
->leftJoin('targets', 'targets.id', '=', 'hinteractions.target_id')->where('herbs.id', $id)
//added below lines
->leftJoin('hinteraction_has_effects', 'hinteraction_has_effects.hinteractons_id', '=', 'hinteractions.id')
->leftJoin('effects', 'hinteraction_has_effects.effects_id', '=', 'effects.id')
->get();
!
推荐阅读
- angular - fontawesome angular package和标准npm package和simple sass有什么区别
- python - 在文件路径中读取时从字符串文字更改为原始字符串文字的替代方法
- pyspark - AWS Glue - GlueContext:从 S3 读取分区数据,将分区添加为 DynamicFrame 的列
- linux - tar 命令未在 linux 中压缩存档文件
- html - 将 div 与另一个 div 对齐
- java - 命令完成后 JSch 会退出吗?
- firebase - Flutter CloudFirestorePlugin.java 使用未经检查或不安全的操作。注意:使用 -Xlint 重新编译:详细信息未选中
- html - 固定高度(表格),溢出的行在第二列
- angular - angular4材料表结果错误中的自定义验证器
- jenkins - 使用共享库时没有这样的 DSL 方法“getVar”