[英]Property [X] does not exist on this collection instance laravel relationship
我正在使用laravel 5.6中的许多功能,当我dd $ phonebooks 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
。
您需要将关系定义更改为hasOne()
,或执行类似的操作:
{{ $phonebook->client->first()->title }}
(或替代):
{{ $phonebook->client->get(0)->title }}
更好地使用has()
$phonebooks = Phonebook::has('client')->get();
查询关系存在 https://laravel.com/docs/5.7/eloquent-relationships#querying-relations
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.