我在 Laravel 5.6 中使用了很多 Realtions,当我添加 $phonebooks 时,我看到所有关系都工作正常,一切都很好,但是当我尝试在视图中显示它们时,我得到了属性在此集合上不存在的错误
这是关系代码
public function client() {
return $this->hasMany('App\Client','id' , 'client_id');
}
这是控制器
public function index()
{ $phonebooks = Phonebook::with('client')->get();
return view('admin.phonebooks.index',compact('phonebooks',$phonebooks));
}
最后,这是我如何尝试将它们展示在视图中
<tbody>
@foreach($phonebooks as $phonebook)
<tr>
<th scope="row">{{$phonebook->id}}</th>
<th scope="row">{{$phonebook->title}}</th>
<td><a href="/admin/phonebooks/{{$phonebook->id}}">{{$phonebook->description}}</a></td>
<td>{{$phonebook->calldate}}</td>
<td>{{$phonebook->created_at->toFormattedDateString()}}</td>
<td>{{ $phonebook->client->title}}</td>
<td>
<div class="btn-group" role="group" aria-label="Basic example">
<a href="{{ URL::to('admin/phonebooks/' . $phonebook->id . '/edit') }}">
<button type="button" class="btn btn-warning">ویراییش</button>
</a>
<form action="{{url('admin/phonebooks', [$phonebook->id])}}" method="POST">
<input type="hidden" name="_method" value="DELETE">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<input type="submit" class="btn btn-danger" value="حذف"/>
</form>
</div>
</td>
</tr>
@endforeach
</tbody>
这是 dd 的结果,只是其中的一部分
Collection {#630 ▼ #items: array:3 [▼
0 => Phonebook {#572 ▼
#fillable: array:5 [▶]
#connection: "mysql"
#table: null
#primaryKey: "id"
#keyType: "int"
+incrementing: true
#with: []
#withCount: []
#perPage: 15
+exists: true
+wasRecentlyCreated: false
#attributes: array:8 [▶]
#original: array:8 [▶]
#changes: []
#casts: []
#dates: []
#dateFormat: null
#appends: []
#dispatchesEvents: []
#observables: []
#relations: array:1 [▼
"client" => Collection {#627 ▼
#items: array:1 [▼
0 => Client {#621 ▼
#connection: "mysql"
#table: null
#primaryKey: "id"
#keyType: "int"
+incrementing: true
#with: []
#withCount: []
#perPage: 15
+exists: true
+wasRecentlyCreated: false
#attributes: array:16 [▼
"id" => 1
就这样下去了。
问题是这一行:
{{ $phonebook->client->title}}
在你看来。
您已将你们的关系设置为hasMany
关系,它将返回模型的集合。
如果你这样做dd($phonebook->client)
,它将返回一个集合,而不是单个模型。
它正在尝试调用该属性title
在集合对象上,而不是模型上。
您需要将关系定义更改为hasOne()
,或者做类似的事情:
{{ $phonebook->client->first()->title }}
(或者替代):
{{ $phonebook->client->get(0)->title }}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)