我使用在laravel 5.6许多关系基本概念,当我DD在$电话簿我看到所有的关系都正常工作,每一件事情是好的,但是当我试图向他们展示鉴于我得到的财产误差在这个集合不存在这里是关系码
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
。
你需要的关系definiation更改为hasOne()
,或者做一些这样的:
{{ $phonebook->client->first()->title }}
(或备选地):
{{ $phonebook->client->get(0)->title }}
最好使用具有()
$phonebooks = Phonebook::has('client')->get();
查询关系存在https://laravel.com/docs/5.7/eloquent-relationships#querying-relations