Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
244 views
in Technique[技术] by (71.8m points)

laravel - Select Specific columns from multiple Table with with() and select ()

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 IlluminateDatabaseQueryException: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'goals.Goal_id' in 'field list'

question from:https://stackoverflow.com/questions/65916366/select-specific-columns-from-multiple-table-with-with-and-select

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...