Wednesday, March 15, 2017

How do I eager load a model off the back of another model?

Hopefully this should add some context to my question. I have 3 models.

My Build Model:

public function buildComment(){
    return $this->hasMany('App\buildComment');
}
public function buildQuestion(){
    return $this->belongsTo('App\buildQuestion');
}

My buildQuestion Model:

public function build(){
        return $this->hasMany('App\Build');
    }

buildComments Model:

public function build(){
    return $this->belongsTo('App\Build');
}

Here is my controller:

public function viewQuestion(buildQuestion $buildQuestion){
    $builds = Build::with('buildComment')->get();

    return view('pages.questionView',compact('buildQuestion', 'builds'));
}

here is my view:

@foreach($buildQuestion->build as $build)
       <ul class="list-group">
           <li class="list-group-item clearfix active">Build suggestion by: </li>
            <li class="list-group-item clearfix">Processor: <a href="/parts/cpu/"></a></li>
            <li class="list-group-item clearfix">Graphics Card: <a href="/parts/gpu/"></a></li>
            <li class="list-group-item clearfix">RAM: <a href="/parts/memory/"></a></li>
            <li class="list-group-item clearfix">Motherboard: <a href="/parts/motherboard/"></a></li>
            <li class="list-group-item clearfix">Power Supply: <a href="/parts/power-supply/"></a></li>
            <li class="list-group-item clearfix">Storage: <a href="/parts/storage/"></a></li>
            <li class="list-group-item clearfix">Optical Drive: <a href="/parts/optical-drive/"></a></li>
            <li class="list-group-item clearfix"><strong>Build Total Price: £</strong></li>
        </ul>
        <!--Placeholder for comments-->
        <p></p>
        <form action="/build-comment/post/" method="POST">
            <div class="form-group">
                <label for="body">Comment </label>
                <textarea class="form-control"  name="body"></textarea>
            </div>
            <input type="hidden" name="_token" value="">
            <button type="submit" class="btn btn-primary">Submit</button>
        </form>
        @endforeach

I am trying to fetch the comments belonging to the build.

The buildQuestion has many builds, the build has many comments.

How can I represent this and retrieve the comments for the build?



via Rick

Advertisement