如何使用Laravel将产品分配到相关类别

时间:2019-12-09 12:39:47

标签: laravel

我正在尝试显示与该类别相关的产品。在我的菜单中,我有一个类别列表,如果我单击此类别,我想查看与此类别相关的产品。我只是在学习laravel可以帮助我。.

数据库:

-category: id, cate_name ,p_id

-product: has Category_id

产品型号:

namespace App;
use Illuminate\Database\Eloquent\Model;

class product extends Model
{

    protected $fillable = [ 'id', 'product_name', 'product_price', 'product_image', 
    'product_brand'];
}

类别模型:

namespace App;
use Illuminate\Database\Eloquent\Model;
class category extends Model
{
    public $table = "category";
    public function childs()
    {
        return $this->hasMany('App\category','p_id');
    }
}

类别视图:

<div class="nav-panel__nav-links nav-links">
    <ul class="nav-links__list">
        @foreach(App\category::with('childs')->where('p_id',0)->get() as $firstmenu)
        <li class="nav-links__item  nav-links__item--has-submenu ">
            <a id="cate" class="nav-links__item-link" href="{{$firstmenu->cate_name}}">
                <div class="nav-links__item-body">
                    {{$firstmenu->cate_name}}
                    <svg class="nav-links__item-arrow" width="9px" height="6px">
                        <use xlink:href="public/assets/images/sprite.svg#arrow-rounded-down-9x6"></use>
                    </svg>
                </div>
            </a>
            <div class="nav-links__submenu nav-links__submenu--type--megamenu nav- 
    links__submenu--size--nl">
                <!-- .megamenu -->
                <div class="megamenu ">
                    <div class="megamenu__body">
                        <div class="row">
                            @foreach($firstmenu->childs as $secondmenu)
                            <div class="col-6">
                                <ul class="megamenu__links megamenu__links--level--0">
                                    <li class="megamenu__item  megamenu__item--with-submenu ">
                                        <a href="">{{$secondmenu->cate_name}}</a>
                                        <ul class="megamenu__links megamenu__links--level--1">

                                            @foreach($secondmenu->childs as $thirdmenu)
                                            <li class="megamenu__item"><a href="">{{$thirdmenu->cate_name}}</a></li>
                                            @endforeach

                                        </ul>
                                    </li>
                                </ul>
                            </div>
                            @endforeach
                        </div>
                    </div>
                </div>
                <!-- .megamenu / end -->
            </div>
        </li>
        @endforeach
    </ul>
</div>

1 个答案:

答案 0 :(得分:0)

根据您的关系类型(一对,多对多,一对一),您可以创建关系, 您可以使用this article