簡體   English   中英

過濾 laravel 中的搜索結果

[英]Filtering search results in laravel

用戶可以訂閱 package 和 package 可以有很多視頻。

除非用戶訂閱 package,否則所有付費視頻均不可見。

請注意:免費視頻無需訂閱即可觀看。

我的問題是,當我想應用搜索查詢時,用戶可以查看我不想要的所有視頻,我希望用戶只查看他訂閱的視頻。

這是我的代碼行:

視頻控制器.php

public function index(Request $request)
{
  $keyword = $request->get('search');
  $perPage = 10;

  if (!empty($keyword)) {
    $videos = Video::where('video_title', 'LIKE', "%$keyword%")
        ->orWhere('video_file', 'LIKE', "%$keyword%")
        ->latest()->paginate($perPage);
  } else {
    $videos = Video::where('video_type', '=', 'Free')->latest()->paginate($perPage);
  }

  return view('video.index', compact('videos'));
}

視頻/index.blade.php

@foreach (auth()->user()->subscriptions as $subscription)
@foreach ($subscription->packages as $package)
    <h4>
        {{ $package->package_name }}
    </h4>
    @foreach ($package->videos as $video)
        <a href="{{ url('/video/' . $video->id) }}">
            {{ $video->video_title }} (Click to view)
        </a>
    @endforeach
@endforeach
@endforeach
@foreach ($videos as $item)
<a href="{{ url('/video/' . $item->id) }}">
    {{ $item->video_title }} (Click to view)
</a>
@endforeach
<div> {!! $videos->appends(['search' => Request::get('search')])->render() !!} </div>

訂閱。php model

  public function user()
  {
    return $this->belongsTo(User::class);
  }

  public function packages()
  {
    return $this->hasMany(Package::class);
  }

用戶.php model

public function subscriptions()
{
  return $this->hasMany(Subscription::class);
}

Package.php model

public function subscription()
{
    return $this->belongsTo(Subscription::class);
}
public function videos()
{
    return $this->belongsToMany(Video::class);
}

視頻.php model

public function packages()
{
    return $this->belongsToMany(Package::class);
}

因此,您必須添加另一個子句來檢查當前用戶的訂閱,而不是只檢查關鍵字。

$videos = Video::whereHas('packages.subscription', function($query) {
        $query->where('subscription.user_id', auth()->id());
    })
    ->where(function($query) use ($keyword) {
        $query->where('video_title', 'LIKE', "%$keyword%")
            ->orWhere('video_file', 'LIKE', "%$keyword%");
    })
    ->latest()
    ->paginate($perPage);

whereHas將檢查視頻是否有訂閱,並且訂閱的 user_id 與當前用戶 id ( auth()->id() ) 相同。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM