如何显示不同数据表的数据?一对多关系

问题描述 投票:0回答:1

所以,我有模型谁有许多上传的视频。Model和models_videos是不同的表。我需要根据每个模型的id来显示它们的视频。

ModelController.Model_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 

我无法获得属于特定型号的视频。对不起,我是新手,还在学习

php mysql database laravel eloquent
1个回答
0
投票

我认为你必须指定与以下内容相关的列。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 对于模型:以下是docs说的。一对一

此外,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
        }   

    }
© www.soinside.com 2019 - 2024. All rights reserved.