【问题标题】:How to use laravel custom model functions?如何使用 laravel 自定义模型函数?
【发布时间】:2019-07-30 17:01:04
【问题描述】:

我有两个模型与视频类别和视频有关系

VideoCats
id |名字

视频
id |姓名 | cat_id

我想在 Model 中创建一个函数,该函数将根据 VideoCat 表中存在的类别显示视频数量。

这是我的模型 VideoCat.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class VideoCat extends Model
{
    public function video()
    {
        return($this->hasMany('App\Video'));
    }

    public function lastfour($id)
    {
        self::with('videos')->where('name', $id)->take(5)->get();
    }    
}

这是我要根据类别显示视频的视图

<div class="row">
  <div class="col-lg-6 col-sm-12" style="position: relative">
    @foreach ($cats as $cat)
    <div>
      <h5>{{$cat->name}}</h5>
    </div>
    <div style="position: relative;margin-bottom: 20px;">
      @foreach ($cat->videos) as $video)
      <div style="position: absolute; width: 100%; height: 100%; background: black; opacity: .5; top: 0; left:0"> 
      </div>

      <a href="/bandvideos/{{ $video->id}}">
        <img width="100%; margin-top: 15px; border-radius: 6px;"  
             src="https://img.youtube.com/vi/{{ $video->youtube_id}}/maxresdefault.jpg" alt="">
        <img src="/photos/play.png" 
             style="position:absolute; top:36%; left:42%; height:30%; width:18%" alt="" />
      </a> 
      @endforeach
    </div>
    @endforeach
  </div>
</div>

【问题讨论】:

  • 错误是什么?抱歉,我不明白这是什么问题。
  • 在创建关系函数期间,您使用video,但您何时调用或使用videos 作为关系。虽然,你的问题对我来说不是很清楚,但据我所知,可能你应该使用video 而不是videos。或者在模型中将 video 函数重命名为 videos
  • 对我来说也更有意义:将函数重命名为 videos()

标签: php laravel eloquent


【解决方案1】:

您的模型不是很清楚,但这是正确的吗:(VideoCat 有很多 Video),那么这应该可以解决问题:

namespace App;

use Illuminate\Database\Eloquent\Model;

class VideoCat extends Model
{
    public function videos()
    {  //           ^^^^^^ [1]
        return $this->hasMany('App\Video', 'cat_id');
    }  //                                  ^^^^^^^^ Specifying the foreign key. [2]

    public function lastfour($id)
    {
        self::with('videos')->where('name', $id)->take(5)->get();
    }

}

注意事项

1 - 您有一对多关系,因此将关系从 video 重命名为 videos 更有意义(VideoCat 有许多 Videos)

2 - 假设你的父模型名为 VideoCat,Laravel 将在你的 videos 表中查找名为 video_cat_id 的字段,而不是你想要使用的 cat_id。为了解决这个问题,您需要在声明关系时指定自定义外键。查看文档的this section

【讨论】:

    猜你喜欢
    • 2013-11-12
    • 2023-03-09
    • 1970-01-01
    • 2018-01-10
    • 2018-03-13
    • 2014-01-23
    • 1970-01-01
    • 2021-01-12
    • 2020-06-21
    相关资源
    最近更新 更多