1

I have 2 tables test and goals. One goal has many tests. I would like to fetch data like below.

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

But I am getting error Illuminate\Database\QueryException: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'goals.Goal_id' in 'field list'

2 Answers 2

1

The goals relation is being eager loaded in a separate query so you will not have access to goals.Goal_id in your main query builder, instead you can modify your with() clause to pick specific columns from eager loaded relation as 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();
Sign up to request clarification or add additional context in comments.

Comments

0

This should work:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.