如何仅显示不适用的类别?

时间:2019-07-18 07:52:25

标签: php laravel

我有类别表,我只想显示在business_category表中不可用的类别, business_category->批准为2。

我的代码:

<div class="col-md-6">
   <select multiple name="categories[]" id="categories" class="form-control @error('categories') is-invalid @enderror" autofocus required>
        @foreach($categories as $category)
            @foreach($business_categories as $business_category)
               @if(($business_category->approved==2) || ($business_category->category_id != $category->id))
                   <option value="{{$category->id}}">{{$category->name}}</option>
               @endif
            @endforeach
        @endforeach
  </select>
</div>

我在控制器中的代码:

$business_categories = BusinessCategories::join('categories', 'categories.id', '=', 'category_id')
    ->where('business_id', $id)
    ->select('categories.name as name', 'approved', 'category_id')
    ->get();

$categories = Categories::where('parent_id', '0')->select('id', 'name')->get();

return view('admin.businesses.edit', with([
    'business_categories' => $business_categories,
    'categories'          => $categories,
]));

但是此代码显示了多次应用或未多次应用的类别。

1 个答案:

答案 0 :(得分:0)

首先,您需要在hasMany模型上建立Categories businessCategories关系:

public function businessCategories()
{
    return $this->hasMany(BusinessCategories::class);
}

您的查询

Categories::orWhereDoesntHave('businessCategories')
    ->orWhereHas('businessCategories', function($query) {
        $query->where('approved', 2);
    })->get();

您可以找到更多雄辩的关系查询信息here