Far*_*had 2 php controller view laravel
我在 laravel 5.6 中使用了很多 realtions,当我添加 $phonebooks 时,我看到所有的关系都正常工作,一切都很好,但是当我尝试在视图中显示它们时,我得到此集合中不存在属性的错误这是关系代码
public function client() {
return $this->hasMany('App\Client','id' , 'client_id');
}
Run Code Online (Sandbox Code Playgroud)
这是控制器
public function index()
{ $phonebooks = Phonebook::with('client')->get();
return view('admin.phonebooks.index',compact('phonebooks',$phonebooks));
}
Run Code Online (Sandbox Code Playgroud)
最后这是我如何尝试在视图中展示它们
<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>
Run Code Online (Sandbox Code Playgroud)
这是 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
Run Code Online (Sandbox Code Playgroud)
就这样下去了。
问题是这一行:
{{ $phonebook->client->title}}
Run Code Online (Sandbox Code Playgroud)
在你看来。
您已将关系设置为hasMany关系,这将返回一组模型。
如果这样做dd($phonebook->client),它将返回一个集合,而不是单个模型。
它试图调用title集合对象上的属性,而不是模型。
您需要将关系定义更改为 a hasOne(),或者执行以下操作:
{{ $phonebook->client->first()->title }}
Run Code Online (Sandbox Code Playgroud)
(或替代):
{{ $phonebook->client->get(0)->title }}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7698 次 |
| 最近记录: |