根据以前的ID获取记录 - Laravel

时间:2017-05-29 21:36:02

标签: javascript php laravel laravel-5.3

我想根据category id获取作物,如果没有JavaScript可以实现,我们会很高兴

显示页面

<div class="cat-list">
    <h3 class="cat-title">
        <a href="/filterByCategory/{{$category->cat_id}}">
            <i class="fa fa-car ln-shadow"></i>
            {{$category->cat_name}}<span class="count">{{$category->count()}}</span>
        </a>
        <span data-target=".cat-id-1" data-toggle="collapse" class="btn-cat-collapsed collapsed">
            <span class=" icon-down-open-big"></span>
        </span>
    </h3>
    <ul class="cat-collapse collapse in cat-id-1">
    @php
        $catID = $category->cat_id;
        //want to fetch crops base on the $catID and display in foreach
    @endphp
    </ul>
</div>

控制器功能

public function index()
{
    $categories = Category::all();

    $crops = Crop::all();

    return view('public.index' , compact('categories' , 'crops'));
}

裁剪模型

public function category() 
{ 
    return $this->belongsTo(Category::class, 'cat_id', 'crop_cat')
}

类别模型

public function category() 
{ 
    return $this->hasmany(Category::class, 'crop_cat','cat_id') 
}

1 个答案:

答案 0 :(得分:0)

您可以将此方法添加到您的类别模型中:

public function crops() {
    return $this->hasMany(Crop::class, 'catID');
}

此功能适用于裁剪模型:

public function category() {
    return $this->belongsTo(Category::class, 'catID');
}

之后,您基本上可以遍历刀片模板上的所有类别,并在此循环中回显当前类别的所有作物。然后,这看起来像这样:

@foreach ($categories as $category)
    {{ $category->name }}

    @foreach ($category->crops as $crop)
         {{ $crop->title }}
    @endforeach
@endforeach

您可以在Laravel here上找到有关雄辩关系的更多信息。