繁体   English   中英

如何在 laravel eloquent 中显示每个类别的视频

[英]how to display video per category in laravel eloquent

model视频

protected $table = 'lokit_video';


protected $fillable = 
[
    'title',
    'cover_img',
    'trailer',
    'url',
    'order_',
    'active',
    'description',
    'lokit_category_id',
    'duration'
];
public function lokit_category(): BelongsTo
{
    return $this->belongsTo(Category::class);
}

model类

protected $table = 'lokit_category';
    protected $fillable = ['name'];

在 controller

public function index(){
       $dataCategory = Category::all();
        $dataVideo = Video::all();
        $video = Video::where('lokit_category_id', $dataCategory)->get();
        dd($video);
        return View('bnpt.content.home',compact('dataCategory','dataVideo'));
    }

当我尝试上面的代码时,代码是 null,如何解决?

[问题]在你的代码中你有

$dataCategory = Category::all();

$video = Video::where('lokit_category_id', $dataCategory)->get();

$dataCategorylokit_category表中所有条目的 model 实例的集合

[解决方案] 您无法在 where 语句中将collection与在您的情况下需要id的字段进行比较。

lokit_category_id应该与类别的 id进行比较。

如果您有lokit_category_id

$videos = Video::where('lokit_category_id', $lokit_category_id)->get();
dd($videos);

如果您有 lokit_category 的名称,请使用该名称获取 id,然后进行查询。

// Get the category for which you want to get all the videos.
$categoryName = 'CATGEORY NAME';

$category = Category::where('name', $categoryName)->first();

$videos = Video::where('lokit_category_id', $category->id)->get();
dd($videos);

[如果您想要某个类别的视频]

在您的类别 Model

public function videos(){
   return $this->hasMany(App\Video::class, 'lokit_catgeory_id', 'id');
}

Controller

使用急切加载,因为它有助于减少查询数量。


$categories = Category::with('videos')->get();

foreach($categories as $category){
    // You can access the videos for the category using the videos relation.
    $category->videos;
}

如果您想获取与所有类别相关的所有视频,则应建立关系。

在 Model Category中:

    public function videos()
    {
        return $this->hasMany(Video::class);
    }

在 controller 方法中:

$dataCategory = Category::all();
return View('bnpt.content.home',compact('dataCategory'));

在视图文件中:

<ul>
@foreach($dataCategory as $category)
    <li><span>{{$category->name}}</span>
        <ul>
           @foreach($category->videos as $video)
                   <li><span>{{$video->name}}</span></li>
           @endforeach
        </ul>
    </li>
@endforeach
</ul>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM