我有商家和地址表以及数据透视表。
当用户点击他们想要查看的业务时,搜索业务ID并使用id我想获取它所属的地址的详细信息。所以我有这样的事情:
public function displayBusiness($id) {
/*
$business = Business::with('addresses')->find($id);
$session = session()->put('key', $id);
$gallery = Gallery::where('business_id', $id)->get();
$location = Location::where('business_id', $id)->get();
$review = Review::where('business_id', $id)->get();
return view('displayBusiness', compact('business', 'address', 'gallery', 'location', 'review', 'items'));
}
我的商业模式:
public function addresses()
{
return $this->belongsToMany('App\Address', 'business_address', 'business_id', 'address_id');
}
地址模型:
public function businesses()
{
return $this->belongsToMany('App\Business', 'business_address', 'business_id', 'address_id');
}
在我看来:
<div class="container container2">
<div id="left" class="logo2">
<img class="images" id="image" src="{{ asset($business->image) }}" />
<form class="upload_form" action="{{ action('ImageController@image') }}" enctype="multipart/form-data" role="form" method="POST">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<input style="width: 100%;height: 100%; opacity: 0;" name="img" id="img" class="img" data-input="false" type="file" data-buttonText="Upload Logo" data-size="sm" data-badge="false" onchange="submitImage();" />
</form>
</div>
<!-- Business Information -->
<div class="info sortable">
<input type="hidden" name="id" value="{{$business->id}}"/>
<p>{{$business->name}}</p>
<p>{{$business->email}}</p>
<p>{{$business->addresses->firstline_address}}</p>
<p>{{$business->addresses->secondline_address}}</p>
<p>{{$business->addresses->town}}</p>
<p>{{$business->addresses->city}}</p>
<p>{{$business->addresses->postcode}}</p>
<p>{{$business->addresses->telephone}}</p>
</div>
但是我收到错误:
此集合实例上不存在属性[firstline_address]。
如何解决这个问题?
答案 0 :(得分:1)
试试这个
$business->addresses()->value('firstline_address');
答案 1 :(得分:1)
给定地址 - business是ManyToMany关系,地址是一个集合,所以请尝试
@foreach( $business->addresses as $address )
<p>{{$address->firstline_address}}</p>
.....
@endforeach
答案 2 :(得分:0)
您不能$business->addresses->firstline_address
,因为$business->addresses
是地址的集合,而不是单个对象
您有两个选择:
选项1:foreach循环:
@forelse({{$business->addresses as $adresse)
<p>{{$adresse->firstline_address}}</p>
<p>{{$adresse->secondline_address}}</p>
<p>{{$adresse->town}}</p>
<p>{{$adresse->city}}</p>
<p>{{$adresse->postcode}}</p>
<p>{{$$adresse->telephone}}</p>
@empty
<p> No Adresses </p>
@endforelse
选项2:您只需要第一个地址
<p>{{$business->name}}</p>
<p>{{$business->email}}</p>
<p>{{$business->addresses->first()->firstline_address}}</p>
<p>{{$business->addresses->first()->secondline_address}}</p>
<p>{{$business->addresses->first()->town}}</p>
<p>{{$business->addresses->first()->city}}</p>
<p>{{$business->addresses->first()->postcode}}</p>
<p>{{$business->addresses->first()->telephone}}</p>