首页 > 解决方案 > 在查询 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 查询。

你有什么主意吗 ?

标签: phpsqllaraveleloquentlaravel-7

解决方案


试试下面的查询,让我知道这是否是你要找的 -

$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();


推荐阅读