在我的控制器中,我使用预先加载来加载所有属性及其相关文件和地址:
public function search_results(Request $request)
{
$Properties = Property::with('Residential', 'File', 'addresses')->get();
return view('result', ['results' => $Properties]);
}
并直接传递到视图上。但是在view.blade.php中如何访问这些相关数据。
以下是我的观点示例,但它似乎与相关数据无关。
@forelse ($results as $result)
<div class="row">
<div class="col-md-7">
@foreach($result->File() as $file)
<a href="#">
<img class="img-responsive" alt="" src="{{ URL::to('/') }}/images/properties/{{$file->filename}}">
</a>
@endforeach
</div>
<div class="col-md-5">
<h3>{{ $result->title }}</h3>
<h4>Subheading</h4>
<p>{{ $result->description }}</p>
<a class="btn btn-primary" href="#">View Property
<span class="glyphicon glyphicon-chevron-right"></span>
</a>
</div>
</div>
这是我的房产模型:
class Property extends Model
{
protected $table = 'properties';
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'user_id', 'is_for_sale','available','title', 'description','price','date_available'
];
public function user()
{
return $this->belongsTo('App\User');
}
public function Residential()
{
return $this->hasOne('App\Residential');
}
/**
* The Addresses that belong to the properties.
*/
public function addresses()
{
return $this->belongsToMany('App\Address');
}
public function File()
{
return $this->hasMany('App\File');
}
}
文件模型
class File extends Model
{
protected $table = 'files';
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'property_id', 'file_type_id','filename','system_filename', 'is-deleted'
];
public function Property()
{
return $this->belongsTo('App\Property');
}
public function File_Type()
{
return $this->belongsTo('App\File_types');
}
}
在视图中处理此类相关数据的正确方法是什么?
答案 0 :(得分:0)
为了你的
@foreach($result->File() as $file)
将其更改为
@foreach($result->File as $file)
。
$result->File()
正在加载与控制器中search_results()
方法相同的关系。