在Laravel中显示表中的一列有很多关系

时间:2019-07-12 09:31:28

标签: php laravel has-many

在我的项目中,属性和视频之间有很多关系。我正在尝试显示属性表中的标题,该标题属于视频表中的相应视频。

properties (id, title)

videos (id, model_id, filename_video)

此处,model_id是指向属性表的外键。使用当前代码,我将显示所有标题。任何帮助表示赞赏。这是我的代码。

Property.php

<?php
namespace App;

use Illuminate\Database\Eloquent\Model;

class Property extends Model
{
    protected $guarded = ['id'];

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

Video.php

<?php
namespace App;

use Illuminate\Database\Eloquent\Model;

class Video extends Model
{
    protected $guarded=['id'];

    public function properties()
    {
        return $this->belongsTo(Property::class);
    }

}

PropertyController.php

public function viewVideos(Property $property, Video $video)
{
    $results = DB::table('properties')
       ->join('videos', 'properties.id', '=', 'videos.model_id')
       ->select('properties.title')
       ->get();

    $video = $property->videos;

    return view('property.videos', compact('video', 'results'));
}

videos.blade.php

<h1 class="font-weight-light text-center text-lg-left mt-4 mb-0">
    Videos for 
    @foreach($results as $result)
        {{$result->title}}
    @endforeach
</h1>

2 个答案:

答案 0 :(得分:1)

尝试这样设置:

Property.php

class Property extends Model
{
    protected $guarded = ['id'];

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

Video.php

class Video extends Model
{
    protected $guarded=['id'];

    public function properties()
    {
        return $this->belongsTo(Property::class, 'model_id');
    }
}

控制器

$results = Property::with('videos')->where('title', $property->title)->get();

答案 1 :(得分:-1)

您应该尝试以下操作:

$results = DB::table('properties')
       ->join('videos', 'properties.id', '=', 'videos.model_id')
       ->pluck('title');