在 Laravel 中使用模型属于两个 Id 来建立关系

时间:2021-04-19 07:15:23

标签: laravel

我有两张桌子

media and trainingVideo.

training video having two column video_id and second_video_id 

videos store in media table.
 
i want two relationship both video in trainigtable.

//模型


// trainingModel

public function media()
    {
        return $this->belongsTo(Media::class, ['video_id', 'second_video']);
    }

// 媒体模型

public function trainingVideos()
    {
        return $this->hasMany(TrainingVideo::class, 'id');
    }

$a = TrainingVideo::with('media')->get();

我想要这段关系中的两个视频。 请帮我解决这个问题。

1 个答案:

答案 0 :(得分:0)

回答

语法:-

$model = Model::with('relatedModel', 'relatedModelTwo')->get();

所以在你的情况下,它可能是这样的。

$a = TrainingVideo::with('media','trainingVideos')->get();

当你 dd($a) 时,你应该会在关系数组属性中看到相关的模型。

要从那里访问关系的属性,只需

$a->media->media_Attribute

$a->trainingVideos->trainingVideos_Attribute

Laravel 关系文档:- https://laravel.com/docs/5.1/eloquent-relationships#one-to-one

在laravel中使用模型belongsTo两个Id建立关系 https://stackoverflow.com

Eloquent: Relationships - Laravel - 网络工匠的 PHP 框架 https://laravel.com

相关问题