如何在 laravel 8 中使用 with 关系在 2 个表中使用条件

how to use condition in 2 tables using with relation in laravel 8

我有两个表,名称分别是课程和招生。现在我想设置如果用户购买课程然后显示承认其他显示课程价格。请检查以下代码:

 $courses = Course::orderby('id', 'desc')->get();
 $admission = Admission::where('users_id', Auth::user()->id)->first() ?: app(Admission::class);            
                
 return view('Backend.Student.courses', compact('courses', 'admission'));

这是我在 blade 文件中的条件:

@if( $course->id == $admission->courses_id )
    <li class="list-inline-item">
        <a href="javascript:void(0)" class="btn btn-info btn-sm"><h5 class="p-0 m-0 text-white"> {{ __('Admitted') }}</h5></a>
    </li>
    @if( !empty($admission->status == 'active') )
    <li class="list-inline-item">
        <a href="{{ route('access.course', $course->slug) }}" class="btn btn-warning btn-sm"><h5 class="p-0 m-0 text-white"> {{ __('Continue Course') }}</h5></a>
    </li>
    @endif
    @else
    <li class="list-inline-item">
        <a href="{{ route('purchase.course', $course->slug) }}" class="btn btn-info btn-sm"><h5 class="p-0 m-0 text-white"> {{ __('Admission Now') }}</h5></a>
    </li>
    <li class="list-inline-item">{{ __('Price') }}: ৳{{ number_format( $course->price , 0 , '.' , ',' ) }} BDT</li>
@endif

这门课程正在运行,但它只显示一门课程。当同一用户购买多门课程时,将显示只有一门课程被录取。但我希望如果用户购买多门课程,则应该显示每门课程都被录取。抱歉我的英语不好,谢谢你的好意。

您只获取了第一个条入学记录,因此只有一条记录。

获取当前登录用户的所有Admission条记录

$courses = Course::latest('id')->get();
$admissions = Admission::where('user_id', Auth::id())->get();

return view('Backend.Student.courses', compact('courses', 'admissions'));

在 blade 视图中,您循环访问用户的录取

@foreach($courses as $course)
    {{-- If the user has purchased course --}}
    @if(in_array($course->id, $admissions->pluck('course_id')->toArray())
        @foreach($admissions as $admission)
            {{-- If the course is active --}}
            @if($admission->course_id === $course->id && $admission->status === 'active')
                <li class="list-inline-item">
                    <a href="{{ route('access.course', $course->slug) }}" class="btn btn-warning btn-sm"><h5 class="p-0 m-0 text-white"> {{ __('Continue Course') }}</h5></a>
                </li>
            @elseif($admission->course_id === $course->id && $admission->status !== 'active')
               {{-- If the course is not active --}}
                <li class="list-inline-item">
                    <a href="javascript:void(0)" class="btn btn-info btn-sm"><h5 class="p-0 m-0 text-white"> {{ __('Admitted') }}</h5></a>
                </li>
            @endif
        @endforeach
    @else        
        {{-- User has not purchased the course --}}
        <li class="list-inline-item">
            <a href="{{ route('purchase.course', $course->slug) }}" class="btn btn-info btn-sm"><h5 class="p-0 m-0 text-white"> {{ __('Admission Now') }}</h5></a>
        </li>
        <li class="list-inline-item">{{ __('Price') }}: ৳{{ number_format( $course->price , 0 , '.' , ',' ) }} BDT</li>
    @endif
@endforeach