我有一个表hobbies
表,在父ID下有多行。在我看来,我的记录完全显示出来。但我希望逐个或单独显示这些行记录。
我的表:
Parent.php
class Parent extends Model
{
public function feature()
{
return $this->hasMany(Feature::class, 'product_id');
}
}
Feature.php
class Feature extends Model
{
public function feat()
{
return $this->belongsTo(Parent::class);
}
}
Controller.php这样
public function display($url)
{
$parent = Parent::where('url', $url)->firstorfail();
$feat = Feature::with(['feat','user'])->get();
return view ('display', compact('parent', 'feat'));
}
display.blade.php
@foreach($feat as $show)
<img alt="{{ $show->col_name }}" src="{{url($show->col_img) }}"/>
@endforeach
答案 0 :(得分:0)
我假设您希望通过给定的网址获得父级(或者是产品)。在您的视图中,您希望显示与此父项关联/相关的所有功能。
首先,如下所示更改模型(假设您的模型存储在app/
下:
class Parent extends Model
{
public function features()
{
return $this->hasMany('App\Feature', 'product_id');
}
}
class Feature extends Model
{
public function parent()
{
return $this->belongsTo('App\Parent');
}
}
现在只需在控制器中搜索您的父级即可:
public function display($url)
{
$parent = Parent::where('url', $url)->firstorfail();
$feature = Feature::where('parent_id', $parent->id)->first();
return view ('display', ['parent' => $parent, 'feature' => $feature]);
}
最后,您可以访问模板文件中的功能,如下所示:
// Show your parent-information
<h1>{{ $parent->name }}</h1>
<img src="{{ $feature->col_img }}" alt="{{ $feature->col_name }}">
我希望这就是你要找的东西!
要在页面的顶部,中间和底部显示随机图片,您可以使用Laravel's array_random-function:
@php
// store your features in a temporary variable
$features = $parent->features;
// collect feature and remove it from array
$feature1 = array_random($features);
array_forget($features, $feature1);
$feature2 = array_random($features);
array_forget($features, $feature1);
$feature3 = array_random($features);
@endphp
<!-- Top -->
<img src="{{ $feature1->col_img }}" alt="{{ $feature1->col_name }}">
<!-- Middle -->
<img src="{{ $feature2->col_img }}" alt="{{ $feature2->col_name }}">
<!-- Bottom -->
<img src="{{ $feature3->col_img }}" alt="{{ $feature3->col_name }}">
我不知道Laravel的array_random
是否以这种方式工作。所以也许你必须以另一种方式删除退回的项目。