【问题标题】:Use query 2 in query 1 to get all data inside one query在查询 1 中使用查询 2 来获取一个查询中的所有数据
【发布时间】:2020-09-11 03:20:31
【问题描述】:

我有 3 张桌子:

*hinteractions (id, name...) *效果(ID,名称...) *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 查询。

你有什么想法吗?

【问题讨论】:

    标签: php sql laravel eloquent laravel-7


    【解决方案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', '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();
    

    HTH!

    【讨论】:

      猜你喜欢
      • 2015-09-12
      • 1970-01-01
      • 2012-01-21
      • 2013-03-04
      • 1970-01-01
      • 1970-01-01
      • 2016-10-28
      • 2023-04-11
      • 1970-01-01
      相关资源
      最近更新 更多