首页 > 解决方案 > 使用 with() 从多个表中选择特定列并选择 ()

问题描述

我有 2 张桌子testgoals. 一个目标有许多测试。我想获取如下数据。

$tests = test::with('goals')
                ->where('Goal_id', $goal_id)
                ->select('test.id as id','goals.Goal_id as goal_id','test.mode as mode')
                ->get();

但我收到错误Illuminate\Database\QueryException: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'goals.Goal_id' in 'field list'

标签: laraveleloquent

解决方案


目标关系被预先加载到单独的查询中,因此您将无法goals.Goal_id在主查询构建器中访问,而是可以修改with()子句以从预先加载的关系中选择特定列作为with('goals:Goal_id,another_column')

$tests = test::with('goals:Goal_id')
                ->where('Goal_id', $goal_id)
                ->select(['test.id as id','test.mode as mode'])
                ->get();

推荐阅读