MTL
MTL

Reputation: 33

Laravel Eloquent ORM alternative to pluck

New to ORMs in general, looking for guidance.

I have 3 tables, and I'm trying to get a list of ID's from my Question table which belongs to my Survey Table (From within my Survey Controller). I can use ORM and pluck, but that only returns the first ID. Any idea how I would go about getting all of the question ID's corresponding to the below query?

When I display the page in a forelse on the view page, it will only show for the first ID over and over. Any Ideas?

$ball = $survey->questions->pluck('id');

Which is used to feed

  $chart = Charts::database($answer->whereIn('question_id', $ball)->get(), 'bar', 'material')
    ->title("")
    ->colors(['#F5A623', '#A9D8D3'])
    ->elementLabel("Answers")
    ->dimensions(0, 250)
    ->groupBy('answer');

Survey Controller

class Survey extends Model
{
    protected $fillable = ['title', 'description', 'user_id'];
    protected $dates = ['deleted_at'];
    protected $table = 'surveys';

    public function questions(){
        return $this->hasMany(Question::class);
    }

    public function user(){
        return $this->belongsTo(User::class);
    }

    public function answers(){
        return $this->hasMany(Answer::class);
    }


}

Answer Controller

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class answer extends Model
{
    protected $fillable = [
        'answer'
    ];

    protected $table = 'answers';

    public function survey(){
        return $this->belongsTo(Survey::class);
    }

    public function question(){
        return $this->belongsTo(Question::class);
    }

}

Question Controller

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Question extends Model
{
    protected $casts = [
    'option_name' => 'array',
    ];

    protected $fillable =['title', 'question_type', 'option_name', 'user_id'];
    public function survey(){
        return $this->belongsTo(Survey::class);
    }

    public function user(){
        return $this->belongsTo(User::class);
    }

    public function answers(){
        return $this->hasMany(Answer::class);
    }

    protected $table = 'questions';
}

Upvotes: 1

Views: 1834

Answers (1)

Moak
Moak

Reputation: 12885

As I'm not completely sure of the issue and the code is incomplete here are some ideas.

  • $balls = $survey->questions()->pluck('id'); will create a collection from the DB.
  • Use ->whereIn('question_id', $balls)->get() when dealing with a collection/array of IDs.
  • You can add a belongsTo(Question::class) to your Answer allowing for $answer->question

Upvotes: 1

Related Questions