【问题标题】:How to get subcategory status and category status on Blade view?如何在 Blade 视图中获取子类别状态和类别状态?
【发布时间】:2022-01-27 17:17:06
【问题描述】:
$categories = Category::with('subcategory')->where('status',1)->take(7)->get();

view()->share('categories', $categories);

型号分类:

protected $fillable =[
    'category_en',
    'category_np',
    'status',
];

public function posts()
{
    return $this->hasMany(Post::class);
}

public function subcategory()
{
    return $this->hasMany(Subcategory::class); // category_id
}

模型子类别:

protected $fillable = [
    'subcategory_en',
    'status',
    'category_id',
    'subcategory_np',
];

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

我的刀片视图:

@foreach ($categories as $item)
    <li>
        <a href="#">{{ $item->category_en }}</a>
                               
        @if ($item->subcategory->count() > 0)
            <ul class="nav-dropdown">
                @foreach ($item->subcategory as $items)
                <li>
                    <a href="#">{{ $items->subcategory_np }}</a>
                </li>                                      
                @endforeach
            </ul>
        @endif
    </li>
@endforeach

我得到了 category 状态 0 但没有得到 subcategory 状态 0。

我想在刀片视图中同时获得 categorysubcategory 状态 0。

我是 laravel 新手,请帮忙。

【问题讨论】:

    标签: php laravel eloquent laravel-8 eloquent-relationship


    【解决方案1】:

    您可以通过像这样更改查询来为您的关系数据添加条件:

    $categories = Category::with(['subcategory' => function($query){
        $query->where('status', 1);
    }])->where('status',1)->take(7)->get();
    

    通过这样做,您将向关系数据添加 where 条件,它只会获取状态为 1 的所有子类别。

    【讨论】:

      猜你喜欢
      • 2019-10-05
      • 1970-01-01
      • 2018-09-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-20
      • 2021-01-31
      • 2020-08-10
      相关资源
      最近更新 更多