[英]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和CallType是我的模型,具有一对一关系。
Call Model 通话模型
public function calltype(){
return $this->hasOne('App\CallType');
}
CallType Model CallType模型
public function call(){
return $this->belongsTo('App\Call');
}
CallsController index method CallsController索引方法
$calls = Call::all();
$user_group = Group::find(Auth::user()->group_id);
return view('settings.calls.index', compact('calls', 'user_group'));
calls.blade.php 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. 当我做
dd($calls)
它没有相关模型。 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
确保索引不是
calls
而是$calls
in clontroller 在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.
我应该在CallType上有一个hasMany,因为每个CallType可以分配许多呼叫。 it should be like this:
应该是这样的:
CallType Model CallType模型
public function calls()
{
return $this->hasMany('App\Call');
}
Call model 通话模式
public function call_type(){
return $this->belongsTo('App\CallType');
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.