Anna Jeanine
Anna Jeanine

Reputation: 4125

Laravel Eloquent Join Querying can't access all variables

I have two models defined (Laravel application): AdviceProtocol and Question which you the tables advice_protocols and questions. The models have been linked together by:

public function userGoal() {
        return $this->hasOne('App\Question', 'id', 'user_goal_id');
    }

I would like to get the following variabels from my query: the advice protocol name, the advice protocol category and questions name. The two tables are linked through a set of ids. The query which I have now is:

public function data(){
        $advicePreparationsQuery = AdviceProtocol::select(['advice_protocols.name', 'advice_protocols.category', 'questions.id'])
        ->join('questions', 'advice_protocols.user_goal_id', '=', 'questions.id')
        ->get();

The questions.id can be retrieved, but when I change the variable to questions.name: nothing is retrieved. My output doesn't give an error, but no values are returned. Could someone please help me to get the value of questions.name?

Upvotes: 0

Views: 446

Answers (3)

Elle H
Elle H

Reputation: 12237

name is ambiguous in your query because you're also selecting advice_protocols.name. You need to give one of them an alias so it knows which column is which when you're trying to access $advicePreparationsQuery->name

$advicePreparationsQuery = AdviceProtocol::select(['advice_protocols.name', 'advice_protocols.category', 'questions.name AS question_name'])
    ->join('questions', 'advice_protocols.user_goal_id', '=', 'questions.id')
    ->get();

Upvotes: 1

Paras
Paras

Reputation: 9465

Try:

$advicePreparationsQuery = AdviceProtocol::select(['advice_protocols.user_goal_id', 'advice_protocols.name', 'advice_protocols.category', 'questions.id', 'questions.name'])
        ->join('questions', 'advice_protocols.user_goal_id', '=', 'questions.id')
        ->get();

Upvotes: 0

Diogo Gomes
Diogo Gomes

Reputation: 2265

I think the problem is that you are not selecting questions.name...

Try:

$advicePreparationsQuery = AdviceProtocol::select([
    'advice_protocols.name', 'advice_protocols.category', 'questions.name'
  ])
  ->join('questions', 'advice_protocols.user_goal_id', '=', 'questions.id')
  ->get();

Upvotes: 0

Related Questions