简体   繁体   中英

Laravel Eloquent not returning all related models

I have a model that is not returning related models, Call and CallType are my models, with a One-to-One relationship.

Call Model

public function calltype(){
    return $this->hasOne('App\CallType');
}

CallType Model

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

CallsController index method

 $calls = Call::all();
    $user_group = Group::find(Auth::user()->group_id);

    return view('settings.calls.index', compact('calls', 'user_group'));

calls.blade.php

@foreach($calls as $call)

   <tr>
     <td>{{$call->call_code}}</td>
     <td>{{$call->call_name}}</td>
     <td>{{$call->calltype->type}}</td>
   </tr>
@endforeach

Calls Migration

Schema::create('calls', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('call_type_id')->unsigned();
            $table->string('call_name');
            $table->string('call_code');
            $table->date('start_date');
            $table->date('end_date');
            $table->string('target_audience')->nullable();
            $table->text('description')->nullable();
            $table->timestamps();
            $table->softDeletes();

            $table->foreign('call_type_id')->references('id')->on('call_types');
        });

CallTypes Migration

 Schema::create('call_types', function (Blueprint $table) {
        //
        $table->increments('id');
        $table->string('type');
        $table->timestamps();
    });

I am getting this error:

Trying to get property of non-object

and when I do dd($calls) it has no related models. What am I doing wrong? please help.

Try this
in blade

 @if(isset($calls))
   @foreach($calls as $call)
    <tr>
     <td>{{$call->call_code}}</td>
     <td>{{$call->call_name}}</td>
     <td>{{$call->calltype->type}}</td>
   </tr>
   @endforeach
@endif

Make sure that index is calls not $calls

in clontroller

return view('calls')->with(['calls'=>$calls,'user_group'=> $user_group]);

First, you should use eager loading to minimize db queries.

Change:

$calls = Call::all();

into

$calls = Call::with('calltype')->get();

The error you get is because probably you don't have calltype set for each call, so you should change in your template:

<td>{{$call->calltype->type}}</td>

into

<td>{{ $call->calltype ? $call->calltype->type : '-' }}</td>

I figured it out. I was supposed to have a hasMany on the CallType, because each CallType can have many Calls assigned to it. it should be like this:

CallType Model

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

Call model

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM