【问题标题】:How to display data from different data tables? One to many reationship如何显示来自不同数据表的数据?一对多关系
【发布时间】:2020-04-26 21:54:41
【问题描述】:

所以,我的模特上传了很多视频。 Model 和 models_videos 是不同的表。我需要根据每个模型的 ID 显示视频。

模型控制器:

 public function index() 
    {
        $models = NewModel::all();

        $model_video = NewModelVideos::all();

        return view('admin.model_new_videos.index')
        ->with('models', $models)
        ->with('model_video', $model_video);

    }

型号

 class NewModel extends Model
    {
 protected $table = 'models';

    protected $guarded  = ['id'];

    protected $sortable = ['id', 'name', 'about'];

    public function videos()
        {
            return $this->hasMany('App\Models\NewModels\NewModelVideos','model_id' ,'id');
        }
    }


    class NewModelVideos extends Model
    {
        use Sortable;

        protected $table = 'models_videos';

        protected $guarded  = ['id'];

        protected $sortable = ['id', 'model_id', 'title', 'video'];

        public function model()
        {
        return $this->belongsTo('App\Models\NewModels\NewModel', 'id');
        }   

    }

并查看:

@foreach($model_video as $model)

    <h1>{{ $model->title }} </h1>
        {{ $model->video }}   

@endforeach 

我无法获取属于特定型号的视频。抱歉,我是新手,还在学习中

【问题讨论】:

  • 您在制作表格时是否指定了foreign 键?

标签: php mysql database laravel eloquent


【解决方案1】:

我认为您必须指定与NewModel相关的列:

class NewModelVideos extends Model
    {
        use Sortable;

        protected $table = 'models_videos';

        protected $guarded  = ['id'];

        protected $sortable = ['id', 'model_id', 'title', 'video'];

        public function model()
        {
        return $this->belongsTo('App\Models\NewModels\NewModel', 'id', 'model_id'); //<-- here
        }   

    }

如果您没有为模型指定 foreign key:这是文档所说的 One To One

此外,Eloquent 假设外键的值应该与父级的 id(或自定义的 $primaryKey)列匹配。也就是说,Eloquent 会在 Phone 记录的 user_id 列中查找用户 id 列的值。如果您希望关系使用 id 以外的值,您可以将第三个参数传递给 hasOne 方法,指定您的自定义键:

return $this->hasOne('App\Phone', 'foreign_key', 'local_key');

这意味着你也可以这样做:

class NewModelVideos extends Model
    {
        use Sortable;

        protected $table = 'models_videos';

        protected $guarded  = ['id'];

        protected $sortable = ['id', 'model_id', 'title', 'video'];

        public function model()
        {
        return $this->hasOne('App\Models\NewModels\NewModel', 'id', 'model_id'); //<-- here
        }   

    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-09-21
    • 2013-01-19
    • 2018-01-22
    • 1970-01-01
    • 2021-12-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多