laravel只搜索id 1

时间:2017-05-16 19:13:10

标签: php laravel

我正在开展一个laravel论坛项目。现在,我所做的是创建了类别和子类别,我将子类别显示在类别下,现在我正在创建线程。因此,对于创建它们的线程,您可以选择它所属的子类别,例如development。

现在,当我打开一个子类别开发,让我们说例如在数据库开发子类别是id 7时,我在子类别模型中创建了一个关系,当我想要显示该子类别中的所有线程时,我循环使用具有多个关系,是模型:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

    class Subcategory extends Model
    {
        protected $fillable=['name', 'category_id'];

        public function threads()
        {
            return $this->hasMany('App\Thread', 'subcategory_id', 'id');
        }
    }

现在当我想循环子类并获得具有该子类别ID的线程时,我这样做:

@extends('layouts.front')

@section('content')




    @foreach($subcategories as $subcategory)

        @foreach($subcategory->threads as $topic)
            <p>{{$topic->name}}</p>
        @endforeach

    @endforeach

@endsection

请记住,例如,subcategory_id为7,我的查询输出

SQL: select * from `threads` where `threads`.`subcategory_id` = 1 and `threads`.`subcategory_id` is not null)

路线:

    Route::group(['middleware' => 'auth'], function () {

        Route::get('category/new', 'CategoryController@newCategory');
        Route::post('category/create', 'CategoryController@store')->name('category.store');

        Route::post('sub/store', 'SubcategoryController@store')->name('subcategory.store');

        Route::get('/category/{id}', 'SubcategoryController@display')->name('subcategory.display');
    });

Controller:

    public function display()
    {
        $threads = Thread::get();
        $subcategories = Subcategory::get();
        return view('thread.index', compact('threads', 'subcategories'));
    }

请您查看代码并尝试向我解释导致问题的原因是什么?

1 个答案:

答案 0 :(得分:0)

控制器:

  public function display($id)
   {
    $threads = Thread::where('subcategory_id',$id)->get();
    return view('thread.index', compact('threads'));
   }

视图:

        @foreach($threads as $topic)
            <p>{{$topic->name}}</p>
        @endforeach